Bewerken

Delen via


BigInteger.TryParse Method

Definition

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

Overloads

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, BigInteger)

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, BigInteger)

Tries to parse a string into a value.

TryParse(ReadOnlySpan<Char>, IFormatProvider, BigInteger)

Tries to parse a span of characters into a value.

TryParse(String, BigInteger)

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, BigInteger)

Tries to convert the representation of a number contained in the specified read-only character span, to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Tries to convert the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(ReadOnlySpan<char> value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public:
 static bool TryParse(ReadOnlySpan<char> value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = System::Numerics::INumberBase<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style, IFormatProvider? provider, out System.Numerics.BigInteger result);
public static bool TryParse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (value As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As BigInteger) As Boolean

Parameters

value
ReadOnlySpan<Char>

The representation of a number as a read-only span of characters.

style
NumberStyles

A bitwise combination of enumeration values that indicates the style elements that can be present in value. A typical value to specify is Integer.

provider
IFormatProvider

An object that supplies culture-specific formatting information about value.

result
BigInteger

When this method returns, contains the BigInteger equivalent to the number that is contained in value, or Zero if the conversion failed. The conversion fails if the value parameter is an empty character span or is not in a format that is compliant with style. This parameter is passed uninitialized.

Returns

true if value was converted successfully; otherwise, false.

Exceptions

style is not a NumberStyles value.

-or-

style includes the AllowHexSpecifier or HexNumber flag along with another value.

Remarks

This overload is like the Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) method, except that it does not throw an exception if the conversion fails. This method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be parsed successfully.

The style parameter defines the style elements (such as white space or a positive or negative sign) that are allowed in the value parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. Depending on the value of style, the value parameter may include the following elements:

[ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

If the style parameter includes AllowHexSpecifier, the value parameter may include the following elements:

[ws]hexdigits[ws]

Elements in square brackets ([ and ]) are optional. The following table describes each element.

Element Description
ws Optional white space. White space can appear at the start of value if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of value if style includes the NumberStyles.AllowTrailingWhite flag.
$ A culture-specific currency symbol. Its position in value is defined by the CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. The currency symbol can appear in value if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the start of value if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of value if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in value to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digits A sequence of digits from 0 through 9.
, A culture-specific group separator. The group separator of the culture specified by provider can appear in value if style includes the NumberStyles.AllowThousands flag.
. A culture-specific decimal point symbol. The decimal point symbol of the culture specified by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digits One or more occurrences of the digit 0. Fractional digits can appear in value only if style includes the NumberStyles.AllowDecimalPoint flag.
E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digits A sequence of digits from 0 through 9. The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigits A sequence of hexadecimal digits from 0 through f, or 0 through F.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

Non-composite NumberStyles values Elements permitted in value in addition to digits
None Decimal digits only.
AllowDecimalPoint The decimal point (.) and fractional_digits elements. However, fractional_digits must consist of only one or more 0 digits, or the method returns false.
AllowExponent The "e" or "E" character, which indicates exponential notation, along with exponential_digits. If value represents a number in exponential notation, it cannot have a non-zero, fractional component.
AllowLeadingWhite The ws element at the start of value.
AllowTrailingWhite The ws element at the end of value.
AllowLeadingSign The sign element before digits.
AllowTrailingSign The sign element after digits.
AllowParentheses The sign element in the form of parentheses enclosing the numeric value.
AllowThousands The group separator (,) element.
AllowCurrencySymbol The currency ($) element.
Currency All elements. However, value cannot represent a hexadecimal number or a number in exponential notation.
Float The ws element at the start or end of value, sign at the start of value, and the decimal point (.) symbol. The value parameter can also use exponential notation.
Number The ws, sign, group separator (,), and decimal point (.) elements.
Any All elements. However, value cannot represent a hexadecimal number.

If the NumberStyles.AllowHexSpecifier flag is used, value must be a hexadecimal value. The only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration has a composite style, HexNumber, that includes both white-space flags.)

The provider parameter is an IFormatProvider implementation. Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. The provider parameter can be any one of the following:

If provider is null, the NumberFormatInfo object for the current culture is used.

See also

Applies to

TryParse(String, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to parse a string into a value.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = IParsable<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out System.Numerics.BigInteger result);
static member TryParse : string * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As BigInteger) As Boolean

Parameters

s
String

The string to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

result
BigInteger

When this method returns, contains the result of successfully parsing s or an undefined value on failure.

Returns

true if s was successfully parsed; otherwise, false.

Applies to

TryParse(ReadOnlySpan<Char>, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to parse a span of characters into a value.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = ISpanParsable<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out System.Numerics.BigInteger result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As BigInteger) As Boolean

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

result
BigInteger

When this method returns, contains the result of successfully parsing s, or an undefined value on failure.

Returns

true if s was successfully parsed; otherwise, false.

Applies to

TryParse(String, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ value, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (string value, out System.Numerics.BigInteger result);
public static bool TryParse (string? value, out System.Numerics.BigInteger result);
static member TryParse : string * BigInteger -> bool
Public Shared Function TryParse (value As String, ByRef result As BigInteger) As Boolean

Parameters

value
String

The string representation of a number.

result
BigInteger

When this method returns, contains the BigInteger equivalent to the number that is contained in value, or zero (0) if the conversion fails. The conversion fails if the value parameter is null or is not of the correct format. This parameter is passed uninitialized.

Returns

true if value was converted successfully; otherwise, false.

Exceptions

value is null.

Examples

The following example uses the TryParse(String, BigInteger) method to instantiate two BigInteger objects. If the conversions succeed, it multiplies each object by another number and then calls the Compare method to determine the relationship between the two objects.

BigInteger number1, number2;
bool succeeded1 = BigInteger.TryParse("-12347534159895123", out number1);
bool succeeded2 = BigInteger.TryParse("987654321357159852", out number2);
if (succeeded1 && succeeded2)
{
   number1 *= 3;
   number2 *= 2;
   switch (BigInteger.Compare(number1, number2))
   {
      case -1:
         Console.WriteLine("{0} is greater than {1}.", number2, number1);
         break;
      case 0:
         Console.WriteLine("{0} is equal to {1}.", number1, number2);
         break;
      case 1:
         Console.WriteLine("{0} is greater than {1}.", number1, number2);
         break;
   }
}
else
{
   if (!succeeded1)
      Console.WriteLine("Unable to initialize the first BigInteger value.");

   if (!succeeded2)
      Console.WriteLine("Unable to initialize the second BigInteger value.");
}
// The example displays the following output:
//      1975308642714319704 is greater than -37042602479685369.
    let mutable number1 = BigInteger.Zero
    let mutable number2 = BigInteger.Zero

    let succeeded1 = BigInteger.TryParse("-12347534159895123", &number1)
    let succeeded2 = BigInteger.TryParse("987654321357159852", &number2)

    if succeeded1 && succeeded2 then
        number1 <- number1 * 3I
        number2 <- number2 * 2I

        match BigInteger.Compare(number1, number2) with
        | -1 -> printfn $"{number2} is greater than {number2}."
        | 0 -> printfn $"{number1} is equal to {number2}."
        | 1
        | _ -> printfn $"{number1} is greater than {number2}."
    else
        if not succeeded1 then
            printfn "Unable to initialize the first BigInteger value."

        if not succeeded2 then
            printfn "Unable to initialize the second BigInteger value."

// The example displays the following output:
//      1975308642714319704 is greater than -37042602479685369.
Dim number1 As BigInteger = BigInteger.Zero
Dim number2 As BigInteger = BigInteger.Zero
Dim succeeded1 As Boolean = BigInteger.TryParse("-12347534159895123", number1)
Dim succeeded2 As Boolean = BigInteger.TryParse("987654321357159852", number2)
If succeeded1 AndAlso succeeded2
   number1 *= 3
   number2 *= 2
   Select Case BigInteger.Compare(number1, number2)
      Case -1
         Console.WriteLine("{0} is greater than {1}.", number2, number1)
      Case 0
         Console.WriteLine("{0} is equal to {1}.", number1, number2)
      Case 1
         Console.WriteLine("{0} is greater than {1}.", number1, number2)
   End Select      
Else
   If Not succeeded1 Then 
      Console.WriteLine("Unable to initialize the first BigInteger value.")
   End If
   If Not succeeded2 Then
      Console.WriteLine("Unable to initialize the second BigInteger value.")
   
   End If
End If
' The example displays the following output:
'      1975308642714319704 is greater than -37042602479685369.

Remarks

The TryParse(String, BigInteger) method is like the Parse(String) method, except that it does not throw an exception if the conversion fails. This method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be successfully parsed.

The value parameter should be the string representation of a decimal number in the following form:

[ws][sign]digits[ws]

Elements in square brackets ([ and ]) are optional. The following table describes each element.

Element Description
ws Optional white space.
sign An optional sign. Valid sign characters are determined by the NumberFormatInfo.NegativeSign and NumberFormatInfo.PositiveSign properties of the current culture.
digits A sequence of decimal digits ranging from 0 to 9.

Note

The string specified by the value parameter cannot contain any group separators or decimal separator, and it cannot have a decimal portion.

The value parameter is interpreted by using the NumberStyles.Integer style. In addition to the decimal digits, only leading and trailing spaces with a leading sign are allowed. To explicitly define the style elements with the culture-specific formatting information that can be present in value, call the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method.

The value parameter is parsed by using the formatting information in a NumberFormatInfo object for the current culture. For more information, see NumberFormatInfo.CurrentInfo.

This overload interprets all digits in the value parameter as decimal digits. To parse the string representation of a hexadecimal number, call the TryParse(String, NumberStyles, IFormatProvider, BigInteger) overload instead.

See also

Applies to

TryParse(ReadOnlySpan<Char>, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to convert the representation of a number contained in the specified read-only character span, to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(ReadOnlySpan<char> value, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (ReadOnlySpan<char> value, out System.Numerics.BigInteger result);
static member TryParse : ReadOnlySpan<char> * BigInteger -> bool
Public Shared Function TryParse (value As ReadOnlySpan(Of Char), ByRef result As BigInteger) As Boolean

Parameters

value
ReadOnlySpan<Char>

The representation of a number as a read-only span of characters.

result
BigInteger

When this method returns, contains the BigInteger equivalent to the number that is contained in value, or zero (0) if the conversion fails. The conversion fails if the value parameter is an empty character span or is not of the correct format. This parameter is passed uninitialized.

Returns

true if value was converted successfully; otherwise, false.

See also

Applies to

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Tries to convert the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public:
 static bool TryParse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result) = System::Numerics::INumberBase<System::Numerics::BigInteger>::TryParse;
public static bool TryParse (string value, System.Globalization.NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result);
public static bool TryParse (string? value, System.Globalization.NumberStyles style, IFormatProvider? provider, out System.Numerics.BigInteger result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (value As String, style As NumberStyles, provider As IFormatProvider, ByRef result As BigInteger) As Boolean

Parameters

value
String

The string representation of a number. The string is interpreted using the style specified by style.

style
NumberStyles

A bitwise combination of enumeration values that indicates the style elements that can be present in value. A typical value to specify is Integer.

provider
IFormatProvider

An object that supplies culture-specific formatting information about value.

result
BigInteger

When this method returns, contains the BigInteger equivalent to the number that is contained in value, or Zero if the conversion failed. The conversion fails if the value parameter is null or is not in a format that is compliant with style. This parameter is passed uninitialized.

Returns

true if the value parameter was converted successfully; otherwise, false.

Exceptions

style is not a NumberStyles value.

-or-

style includes the AllowHexSpecifier or HexNumber flag along with another value.

Examples

The following example makes some calls to the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method using various combinations of values for the style and provider parameters.

string numericString;
BigInteger number = BigInteger.Zero;

// Call TryParse with default values of style and provider.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer,
                       null, out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with the default value of style and
// a provider supporting the tilde as negative sign.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
// Method returns false because of presence of negative sign.
numericString = "  -500   ";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
                        new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowHexSpecifier,
                        null, out number))
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a negative hex value.
// Conversion fails because of presence of negative sign.
numericString = "-3af";
if (BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only NumberStyles.None.
// Conversion fails because of presence of white space and sign.
numericString = " -300 ";
if (BigInteger.TryParse(numericString, NumberStyles.None,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion succeeds because the string is properly formatted
// For the fr-FR culture.
numericString = "9 031 425 666 123 546,00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);
// The example displays the following output:
//    '  -300   ' was converted to -300.
//    Conversion of '  -300   ' to a BigInteger failed.
//    Conversion of '  -500   ' to a BigInteger failed.
//    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
//    Conversion of '-3af' to a BigInteger failed.
//    Conversion of ' -300 ' to a BigInteger failed.
//    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
//    '9 031 425 666 123 546,00' was converted to 9031425666123546.
    // Call TryParse with default values of style and provider.
    let numericString = "  -300   "

    match BigInteger.TryParse(numericString, NumberStyles.Integer, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with the default value of style and
    // a provider supporting the tilde as negative sign.
    let numericString = "  -300   "

    match BigInteger.TryParse(numericString, NumberStyles.Integer, new BigIntegerFormatProvider()) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
    // Method returns false because of presence of negative sign.
    let numericString = "  -500   "

    match
        BigInteger.TryParse(
            numericString,
            NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite,
            new BigIntegerFormatProvider()
        )
    with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with AllowHexSpecifier and a hex value.
    let numericString = "F14237FFAAC086455192"

    match BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}, or 0x{number:x}."
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with AllowHexSpecifier and a negative hex value.
    // Conversion fails because of presence of negative sign.
    let numericString = "-3af"

    match BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}, or 0x{number:x}."
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with only NumberStyles.None.
    // Conversion fails because of presence of white space and sign.
    let numericString = " -300 "

    match BigInteger.TryParse(numericString, NumberStyles.None, new BigIntegerFormatProvider()) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
    // Conversion fails because the string is formatted for the en-US culture.
    let numericString = "9,031,425,666,123,546.00"

    match BigInteger.TryParse(numericString, NumberStyles.Any, new CultureInfo("fr-FR")) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

    // Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
    // Conversion succeeds because the string is properly formatted
    // For the fr-FR culture.
    let numericString = "9 031 425 666 123 546,00"

    match BigInteger.TryParse(numericString, NumberStyles.Any, new CultureInfo("fr-FR")) with
    | true, number -> printfn $"The string '{numericString}' parses to {number}"
    | _ -> printfn $"Conversion of {numericString} to a BigInteger failed."

// The example displays the following output:
//    '  -300   ' was converted to -300.
//    Conversion of '  -300   ' to a BigInteger failed.
//    Conversion of '  -500   ' to a BigInteger failed.
//    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
//    Conversion of '-3af' to a BigInteger failed.
//    Conversion of ' -300 ' to a BigInteger failed.
//    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
//    '9 031 425 666 123 546,00' was converted to 9031425666123546.
Dim numericString As String
Dim number As BigInteger = BigInteger.Zero

' Call TryParse with default values of style and provider.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with the default value of style and 
' a provider supporting the tilde as negative sign.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
' Method returns false because of presence of negative sign.
numericString = "  -500   "
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite,
                    New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192"
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowHexSpecifier,
                    Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a negative hex value.
' Conversion fails because of presence of negative sign.
numericString = "-3af"
If BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only NumberStyles.None.
' Conversion fails because of presence of white space and sign.
numericString = " -300 "
If BigInteger.TryParse(numericString, NumberStyles.None,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If 
                                            
' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If

' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion succeeds because the string is properly formatted 
' For the fr-FR culture.
numericString = "9 031 425 666 123 546,00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If
' The example displays the following output:
'    '  -300   ' was converted to -300.
'    Conversion of '  -300   ' to a BigInteger failed.
'    Conversion of '  -500   ' to a BigInteger failed.
'    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
'    Conversion of '-3af' to a BigInteger failed.
'    Conversion of ' -300 ' to a BigInteger failed.
'    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
'    '9 031 425 666 123 546,00' was converted to 9031425666123546.

A number of the individual calls to the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method pass an instance of the following BigIntegerFormatProvider class, which defines a tilde (~) as the negative sign.

public class BigIntegerFormatProvider : IFormatProvider
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(NumberFormatInfo))
      {
         NumberFormatInfo numberFormat = new NumberFormatInfo();
         numberFormat.NegativeSign = "~";
         return numberFormat;
      }
      else
      {
         return null;
      }
   }
}
type BigIntegerFormatProvider() =
    interface IFormatProvider with
        member _.GetFormat(formatType: Type) =
            if formatType = typeof<NumberFormatInfo> then
                let numberFormat = new NumberFormatInfo()
                numberFormat.NegativeSign <- "~"
                numberFormat
            else
                null
Public Class BigIntegerFormatProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
                            Implements IFormatProvider.GetFormat
      If formatType Is GetType(NumberFormatInfo) Then
         Dim numberFormat As New NumberFormatInfo
         numberFormat.NegativeSign = "~"
         Return numberFormat
      Else
         Return Nothing
      End If      
   End Function
End Class

Remarks

The TryParse(String, NumberStyles, IFormatProvider, BigInteger) method is like the Parse(String, NumberStyles, IFormatProvider) method, except that it does not throw an exception if the conversion fails. This method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be parsed successfully.

The style parameter defines the style elements (such as white space or a positive or negative sign) that are allowed in the value parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. Depending on the value of style, the value parameter may include the following elements:

[ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

If the style parameter includes AllowHexSpecifier, the value parameter may include the following elements:

[ws]hexdigits[ws]

Elements in square brackets ([ and ]) are optional. The following table describes each element.

Element Description
ws Optional white space. White space can appear at the start of value if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of value if style includes the NumberStyles.AllowTrailingWhite flag.
$ A culture-specific currency symbol. Its position in the string is defined by the CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. The currency symbol can appear in value if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the start of value if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of value if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in value to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digits A sequence of digits from 0 through 9.
, A culture-specific group separator. The group separator of the culture specified by provider can appear in value if style includes the NumberStyles.AllowThousands flag.
. A culture-specific decimal point symbol. The decimal point symbol of the culture specified by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digits One or more occurrences of the digit 0. Fractional digits can appear in value only if style includes the NumberStyles.AllowDecimalPoint flag.
E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digits A sequence of digits from 0 through 9. The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigits A sequence of hexadecimal digits from 0 through f, or 0 through F.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

A string with decimal digits only (which corresponds to the NumberStyles.None flag) always parses successfully. Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in this input string. The following table indicates how individual NumberStyles members affect the elements that may be present in value.

Non-composite NumberStyles values Elements permitted in value in addition to digits
None Decimal digits only.
AllowDecimalPoint The decimal point (.) and fractional_digits elements. However, fractional_digits must consist of only one or more 0 digits, or the method returns false.
AllowExponent The "e" or "E" character, which indicates exponential notation, along with exponential_digits. If value represents a number in exponential notation, it cannot have a non-zero, fractional component.
AllowLeadingWhite The ws element at the start of value.
AllowTrailingWhite The ws element at the end of value.
AllowLeadingSign The sign element before digits.
AllowTrailingSign The sign element after digits.
AllowParentheses The sign element in the form of parentheses enclosing the numeric value.
AllowThousands The group separator (,) element.
AllowCurrencySymbol The currency ($) element.
Currency All elements. However, value cannot represent a hexadecimal number or a number in exponential notation.
Float The ws element at the start or end of value, sign at the start of value, and the decimal point (.) symbol. The value parameter can also use exponential notation.
Number The ws, sign, group separator (,), and decimal point (.) elements.
Any All elements. However, value cannot represent a hexadecimal number.

Important

If you use the TryParse method to round-trip the string representation of a BigInteger value that was output by the ToString method, you should use the BigInteger.ToString(String) method with the "R" format specifier to generate the string representation of the BigInteger value. Otherwise, the string representation of the BigInteger preserves only the 50 most significant digits of the original value, and data may be lost when you use the TryParse method to restore the BigInteger value.

If the NumberStyles.AllowHexSpecifier flag is used, value must be a hexadecimal value. The only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration has a composite style, HexNumber, that includes both white-space flags.)

Note

If value is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. This causes the conversion to fail.

If value is a hexadecimal string, the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method interprets value as a negative number stored by using two's complement representation if its first two hexadecimal digits are greater than or equal to 0x80. In other words, the method interprets the highest-order bit of the first byte in value as the sign bit. To make sure that a hexadecimal string is correctly interpreted as a positive number, the first digit in value must have a value of zero. For example, the method interprets 0x80 as a negative value, but it interprets either 0x080 or 0x0080 as a positive value. The following example illustrates the difference between hexadecimal strings that represent negative and positive values.

using System;
using System.Globalization;
using System.Numerics;

public class Example
{
   public static void Main()
   {
      string[] hexStrings = { "80", "E293", "F9A2FF", "FFFFFFFF",
                              "080", "0E293", "0F9A2FF", "0FFFFFFFF",
                              "0080", "00E293", "00F9A2FF", "00FFFFFFFF" };
      BigInteger number = BigInteger.Zero;

      foreach (string hexString in hexStrings)
      {
         if (BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier,
                                 null, out number))
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
         else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString);
      }
   }
}
// The example displays the following output:
//       Converted 0x80 to -128.
//       Converted 0xE293 to -7533.
//       Converted 0xF9A2FF to -417025.
//       Converted 0xFFFFFFFF to -1.
//       Converted 0x080 to 128.
//       Converted 0x0E293 to 58003.
//       Converted 0x0F9A2FF to 16360191.
//       Converted 0x0FFFFFFFF to 4294967295.
//       Converted 0x0080 to 128.
//       Converted 0x00E293 to 58003.
//       Converted 0x00F9A2FF to 16360191.
//       Converted 0x00FFFFFFFF to 4294967295.
open System.Globalization
open System.Numerics

let hexStrings =
    [| "80"
       "E293"
       "F9A2FF"
       "FFFFFFFF"
       "080"
       "0E293"
       "0F9A2FF"
       "0FFFFFFFF"
       "0080"
       "00E293"
       "00F9A2FF"
       "00FFFFFFFF" |]

for hexString in hexStrings do
    match BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier, null) with
    | true, number -> printfn $"Converted 0x{hexString} to {number}."
    | _ -> printfn $"Cannot convert '{hexString}' to a BigInteger."

// The example displays the following output:
//       Converted 0x80 to -128.
//       Converted 0xE293 to -7533.
//       Converted 0xF9A2FF to -417025.
//       Converted 0xFFFFFFFF to -1.
//       Converted 0x080 to 128.
//       Converted 0x0E293 to 58003.
//       Converted 0x0F9A2FF to 16360191.
//       Converted 0x0FFFFFFFF to 4294967295.
//       Converted 0x0080 to 128.
//       Converted 0x00E293 to 58003.
//       Converted 0x00F9A2FF to 16360191.
//       Converted 0x00FFFFFFFF to 4294967295.
Imports System.Globalization
Imports System.Numerics

Module Example
   Public Sub Main()
      Dim hexStrings() As String = { "80", "E293", "F9A2FF", "FFFFFFFF", 
                                     "080", "0E293", "0F9A2FF", "0FFFFFFFF",  
                                     "0080", "00E293", "00F9A2FF", "00FFFFFFFF" }
      Dim number As BigInteger = BigInteger.Zero
      
      For Each hexString As String In hexStrings
         If BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier, 
                                Nothing, number) Then
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number)
         Else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString)
         End If
      Next         
   End Sub
End Module
' The example displays the following output:
'       Converted 0x80 to -128.
'       Converted 0xE293 to -7533.
'       Converted 0xF9A2FF to -417025.
'       Converted 0xFFFFFFFF to -1.
'       Converted 0x080 to 128.
'       Converted 0x0E293 to 58003.
'       Converted 0x0F9A2FF to 16360191.
'       Converted 0x0FFFFFFFF to 4294967295.
'       Converted 0x0080 to 128.
'       Converted 0x00E293 to 58003.
'       Converted 0x00F9A2FF to 16360191.
'       Converted 0x00FFFFFFFF to 4294967295.

The provider parameter is an IFormatProvider implementation. Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. The provider parameter can be any one of the following:

If provider is null, the NumberFormatInfo object for the current culture is used.

See also

Applies to