Επεξεργασία

Κοινή χρήση μέσω


BigInteger.Parse Method

Definition

Converts the string representation of a number to its BigInteger equivalent.

Overloads

Parse(String)

Converts the string representation of a number to its BigInteger equivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parses a span of characters into a value.

Parse(String, NumberStyles)

Converts the string representation of a number in a specified style to its BigInteger equivalent.

Parse(String, IFormatProvider)

Converts the string representation of a number in a specified culture-specific format to its BigInteger equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converts the representation of a number, contained in the specified read-only span of characters, in a specified style to its BigInteger equivalent.

Parse(String, NumberStyles, IFormatProvider)

Converts the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent.

Parse(String)

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

Converts the string representation of a number to its BigInteger equivalent.

public:
 static System::Numerics::BigInteger Parse(System::String ^ value);
public static System.Numerics.BigInteger Parse (string value);
static member Parse : string -> System.Numerics.BigInteger
Public Shared Function Parse (value As String) As BigInteger

Parameters

value
String

A string that contains the number to convert.

Returns

A value that is equivalent to the number specified in the value parameter.

Exceptions

value is null.

value is not in the correct format.

Examples

The following example uses the Parse(String) method to instantiate two BigInteger objects. It multiplies each object by another number and then calls the Compare method to determine the relationship between the two values.

string stringToParse = String.Empty;
try
{
   // Parse two strings.
   string string1, string2;
   string1 = "12347534159895123";
   string2 = "987654321357159852";
   stringToParse = string1;
   BigInteger number1 = BigInteger.Parse(stringToParse);
   Console.WriteLine("Converted '{0}' to {1:N0}.", stringToParse, number1);
   stringToParse = string2;
   BigInteger number2 = BigInteger.Parse(stringToParse);
   Console.WriteLine("Converted '{0}' to {1:N0}.", stringToParse, number2);
   // Perform arithmetic operations on the two numbers.
   number1 *= 3;
   number2 *= 2;
   // Compare the numbers.
   int result = BigInteger.Compare(number1, number2);
   switch (result)
   {
      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;
   }
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse {0}.", stringToParse);
}
// The example displays the following output:
//    Converted '12347534159895123' to 12,347,534,159,895,123.
//    Converted '987654321357159852' to 987,654,321,357,159,852.
//    1975308642714319704 is greater than 37042602479685369.
    let mutable stringToParse = ""

    try
        // Parse two strings.
        let string1 = "12347534159895123"
        let string2 = "987654321357159852"
        stringToParse <- string1
        let number1 = BigInteger.Parse stringToParse
        printfn $"Converted '{stringToParse}' to {number1:N0}."
        stringToParse <- string2
        let number2 = BigInteger.Parse stringToParse
        printfn $"Converted '{stringToParse}' to {number2:N0}."
        // Perform arithmetic operations on the two numbers.
        let number1 = number1 * bigint 3
        let number2 = number2 * bigint 2
        // Compare the numbers.
        let result = BigInteger.Compare(number1, number2)

        match result with
        | -1 -> printfn $"{number2:N0} is greater than {number1:N0}."
        | 0 -> printfn $"{number1:N0} is equal to {number2:N0}."
        | 1
        | _ -> printfn $"{number1:N0} is greater than {number2:N0}."
    with :? FormatException ->
        printfn $"Unable to parse {stringToParse}."

// The example displays the following output:
//    Converted '12347534159895123' to 12,347,534,159,895,123.
//    Converted '987654321357159852' to 987,654,321,357,159,852.
//    1975308642714319704 is greater than 37042602479685369.
Dim stringToParse As String = String.Empty
Try
   ' Parse two strings.
   Dim string1, string2 As String
   string1 = "12347534159895123"
   string2 = "987654321357159852"
   stringToParse = string1
   Dim number1 As BigInteger = BigInteger.Parse(stringToParse)
   Console.WriteLine("Converted '{0}' to {1:N0}.", stringToParse, number1)
   stringToParse = string2
   Dim number2 As BigInteger = BigInteger.Parse(stringToParse)
   Console.WriteLine("Converted '{0}' to {1:N0}.", stringToParse, number2)
   ' Perform arithmetic operations on the two numbers.
   number1 *= 3
   number2 *= 2
   ' Compare the numbers.
   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      
Catch e As FormatException
   Console.WriteLine("Unable to parse {0}.", stringToParse)
End Try
' The example displays the following output:
'    Converted '12347534159895123' to 12,347,534,159,895,123.
'    Converted '987654321357159852' to 987,654,321,357,159,852.
'    1975308642714319704 is greater than 37042602479685369.

Remarks

The value parameter should be the string representation of a 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 digits ranging from 0 to 9. Any leading zeros are ignored.

Note

The string specified by the value parameter is interpreted by using the NumberStyles.Integer style. It cannot contain any group separators or decimal separator, and it cannot have a decimal portion.

The value parameter is parsed by using the formatting information in a System.Globalization.NumberFormatInfo object that is initialized for the current system culture. For more information, see NumberFormatInfo.CurrentInfo. To parse a string by using the formatting information of a specific culture, use the Parse(String, IFormatProvider) method.

Important

If you use the Parse 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 Parse method to restore the BigInteger value.

See also

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Parses a span of characters into a value.

public:
 static System::Numerics::BigInteger Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::Numerics::BigInteger>::Parse;
public static System.Numerics.BigInteger Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> System.Numerics.BigInteger
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As BigInteger

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

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

Returns

The result of parsing s.

Implements

Applies to

Parse(String, NumberStyles)

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

Converts the string representation of a number in a specified style to its BigInteger equivalent.

public:
 static System::Numerics::BigInteger Parse(System::String ^ value, System::Globalization::NumberStyles style);
public static System.Numerics.BigInteger Parse (string value, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> System.Numerics.BigInteger
Public Shared Function Parse (value As String, style As NumberStyles) As BigInteger

Parameters

value
String

A string that contains a number to convert.

style
NumberStyles

A bitwise combination of the enumeration values that specify the permitted format of value.

Returns

A value that is equivalent to the number specified in the value parameter.

Exceptions

style is not a NumberStyles value.

-or-

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

value is null.

value does not comply with the input pattern specified by NumberStyles.

Examples

The following example illustrates calls to the Parse(String, NumberStyles) method with several possible values for the style parameter. It illustrates how to interpret a string as a hexadecimal value, and how to disallow spaces and sign symbols.

BigInteger number;
// Method should succeed (white space and sign allowed)
number = BigInteger.Parse("   -68054   ", NumberStyles.Integer);
Console.WriteLine(number);
// Method should succeed (string interpreted as hexadecimal)
number = BigInteger.Parse("68054", NumberStyles.AllowHexSpecifier);
Console.WriteLine(number);
// Method call should fail: sign not allowed
try
{
   number = BigInteger.Parse("   -68054  ", NumberStyles.AllowLeadingWhite
                                            | NumberStyles.AllowTrailingWhite);
   Console.WriteLine(number);
}
catch (FormatException e)
{
   Console.WriteLine(e.Message);
}
// Method call should fail: white space not allowed
try
{
   number = BigInteger.Parse("   68054  ", NumberStyles.AllowLeadingSign);
   Console.WriteLine(number);
}
catch (FormatException e)
{
   Console.WriteLine(e.Message);
}
//
// The method produces the following output:
//
//     -68054
//     426068
//     Input string was not in a correct format.
//     Input string was not in a correct format.
    let number = BigInteger.Parse("   -68054   ", NumberStyles.Integer)
    printfn $"{number}"
    let number = BigInteger.Parse("68054", NumberStyles.AllowHexSpecifier)
    printfn $"{number}"

    try
        let number =
            BigInteger.Parse("   -68054  ", NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite)

        printfn $"{number}"
    with :? FormatException as e ->
        printfn $"{e.Message}"

    try
        let number = BigInteger.Parse("   68054  ", NumberStyles.AllowLeadingSign)
        printfn $"{number}"
    with :? FormatException as e ->
        printfn $"{e.Message}"
// The method produces the following output:
//     -68054
//     426068
//     Input string was not in a correct format.
//     Input string was not in a correct format.
Dim number As BigInteger 
' Method should succeed (white space and sign allowed)
number = BigInteger.Parse("   -68054   ", NumberStyles.Integer)
Console.WriteLine(number)
' Method should succeed (string interpreted as hexadecimal)
number = BigInteger.Parse("68054", NumberStyles.AllowHexSpecifier)
Console.WriteLine(number)
' Method call should fail: sign not allowed
Try
   number = BigInteger.Parse("   -68054  ", NumberStyles.AllowLeadingWhite _
                                            Or NumberStyles.AllowTrailingWhite)
   Console.WriteLine(number)
Catch e As FormatException
   Console.WriteLine(e.Message)
End Try                                                     
' Method call should fail: white space not allowed
Try
   number = BigInteger.Parse("   68054  ", NumberStyles.AllowLeadingSign)
   Console.WriteLine(number)
Catch e As FormatException
   Console.WriteLine(e.Message)
End Try    
'
' The method produces the following output:
'
'     -68054
'     426068
'     Input string was not in a correct format.
'     Input string was not in a correct format.

Remarks

The style parameter defines the style elements (such as white space, the positive or negative sign symbol, the group separator symbol, or the decimal point symbol) that are allowed in the value parameter for the parse operation to succeed. styles must be a combination of bit flags from the NumberStyles enumeration. The style parameter makes this method overload useful when value contains the string representation of a hexadecimal value, when the number system (decimal or hexadecimal) represented by value is known only at run time, or when you want to disallow white space or a sign symbol in value.

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 style includes NumberStyles.AllowHexSpecifier, the value parameter may contain 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, and it can appear 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 NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. The current culture's 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

fractional_digits

exponential_digits
A sequence of digits from 0 through 9. For fractional_digits, only the digit 0 is valid.
, A culture-specific group separator symbol. The current culture's group separator can appear in value if style includes the NumberStyles.AllowThousands flag.
. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in value if style includes the NumberStyles.AllowDecimalPoint flag. Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, a FormatException is thrown.
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.
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 digits only (which corresponds to the NumberStyles.None style) always parses successfully. Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in the input string. The following table indicates how individual NumberStyles members affect the elements that may be present in value.

NumberStyles value Elements permitted in value in addition to digits
None The digits element only.
AllowDecimalPoint The decimal point (.) and fractional-digits elements.
AllowExponent The "e" or "E" character, which indicates exponential notation, along with exponential_digits.
AllowLeadingWhite The ws element at the start of value.
AllowTrailingWhite The ws element at the end of value.
AllowLeadingSign The sign element at the start of value.
AllowTrailingSign The sign element at the end of value.
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 Parse 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 Parse method to restore the BigInteger value.

Unlike the other NumberStyles values, which allow for, but do not require, the presence of particular style elements in value, the NumberStyles.AllowHexSpecifier style value means that the individual numeric characters in value are always interpreted as hexadecimal characters. Valid hexadecimal characters are 0-9, A-F, and a-f. The only other flags that can be combined with the style parameter are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number 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 Parse(String, NumberStyles) 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" };
      foreach (string hexString in hexStrings)
      {
         BigInteger number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier);
         Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
      }
   }
}
// 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
    let number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier)
    printfn $"Converted 0x{hexString} to {number:N0}."
// 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" }
      For Each hexString As String In hexStrings
         Dim number As BigInteger = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier)
         Console.WriteLine("Converted 0x{0} to {1}.", hexString, number)
      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 value parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. To specify the culture whose formatting information is used for the parse operation, call the Parse(String, NumberStyles, IFormatProvider) overload.

See also

Applies to

Parse(String, IFormatProvider)

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

Converts the string representation of a number in a specified culture-specific format to its BigInteger equivalent.

public:
 static System::Numerics::BigInteger Parse(System::String ^ value, IFormatProvider ^ provider);
public:
 static System::Numerics::BigInteger Parse(System::String ^ value, IFormatProvider ^ provider) = IParsable<System::Numerics::BigInteger>::Parse;
public static System.Numerics.BigInteger Parse (string value, IFormatProvider provider);
public static System.Numerics.BigInteger Parse (string value, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> System.Numerics.BigInteger
Public Shared Function Parse (value As String, provider As IFormatProvider) As BigInteger

Parameters

value
String

A string that contains a number to convert.

provider
IFormatProvider

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

Returns

A value that is equivalent to the number specified in the value parameter.

Implements

Exceptions

value is null.

value is not in the correct format.

Examples

The following examples show two ways to define the tilde (~) as a negative sign for formatting BigInteger values. Note that to display the BigInteger values in the same format as the original strings, your code must call the BigInteger.ToString(IFormatProvider) method and pass it the NumberFormatInfo object that provides formatting information.

The first example defines a class that implements IFormatProvider and uses the GetFormat method to return the NumberFormatInfo object that provides formatting information.

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 = 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

A BigInteger object can then be instantiated with the following code:

BigInteger number = BigInteger.Parse("~6354129876", new BigIntegerFormatProvider());
// Display value using same formatting information
Console.WriteLine(number.ToString(new BigIntegerFormatProvider()));
// Display value using formatting of current culture
Console.WriteLine(number);
let number = BigInteger.Parse("~6354129876", BigIntegerFormatProvider())
printfn $"{number.ToString(BigIntegerFormatProvider())}"
printfn $"{number}"
Dim number As BigInteger = BigInteger.Parse("~6354129876", New BigIntegerFormatProvider)
' Display value using same formatting information
Console.WriteLine(number.ToString(New BigIntegerFormatProvider))
' Display value using formatting of current culture
Console.WriteLine(number)

The second example is more straightforward. It passes the NumberFormatInfo object that provides formatting information to the provider parameter.

NumberFormatInfo fmt = new NumberFormatInfo();
fmt.NegativeSign = "~";

BigInteger number = BigInteger.Parse("~6354129876", fmt);
// Display value using same formatting information
Console.WriteLine(number.ToString(fmt));
// Display value using formatting of current culture
Console.WriteLine(number);
let fmt = NumberFormatInfo()
fmt.NegativeSign <- "~"

let number = BigInteger.Parse("~6354129876", fmt)
printfn $"{number.ToString fmt}"
printfn $"{number}"
Dim fmt As New NumberFormatInfo()
fmt.NegativeSign = "~"

Dim number As BigInteger = BigInteger.Parse("~6354129876", fmt)
' Display value using same formatting information
Console.WriteLine(number.ToString(fmt))
' Display value using formatting of current culture
Console.WriteLine(number)

Remarks

The value parameter should be the string representation of a 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 NumberFormatInfo object that is returned by the provider object's GetFormat method.
digits A sequence of digits ranging from 0 to 9. Any leading zeros are ignored.

Note

The string specified by the value parameter is interpreted using the NumberStyles.Integer style. It cannot contain any group separators or decimal separator, and it cannot have a decimal portion.

Important

If you use the Parse 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 Parse method to restore the BigInteger value.

The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information. When the Parse(String, IFormatProvider) method is invoked, it calls the provider parameter's GetFormat method and passes it a Type object that represents the NumberFormatInfo type. The GetFormat method then returns the NumberFormatInfo object that provides information about the format of the value parameter. There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

  • You can pass a CultureInfo object that represents the culture that supplies formatting information. Its GetFormat method returns the NumberFormatInfo object that provides numeric formatting information for that culture.

  • You can pass the actual NumberFormatInfo object that provides numeric formatting information. (Its implementation of GetFormat just returns itself.)

  • You can pass a custom object that implements IFormatProvider. Its GetFormat method instantiates and returns the NumberFormatInfo object that provides formatting information.

If provider is null, the formatting of value is interpreted based on the NumberFormatInfo object of the current culture.

See also

Applies to

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Converts the representation of a number, contained in the specified read-only span of characters, in a specified style to its BigInteger equivalent.

public static System.Numerics.BigInteger Parse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static System.Numerics.BigInteger Parse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> System.Numerics.BigInteger
Public Shared Function Parse (value As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As BigInteger

Parameters

value
ReadOnlySpan<Char>

A read-only span of characters that contains the number to convert.

style
NumberStyles

A bitwise combination of the enumeration values that specify the permitted format of value.

provider
IFormatProvider

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

Returns

A value that is equivalent to the number specified in the value parameter.

Implements

Exceptions

style is not a NumberStyles value.

-or-

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

value is null.

value does not comply with the input pattern specified by style.

Remarks

The style parameter defines the style elements (such as white space, the positive or negative sign symbol, the group separator symbol, or the decimal point symbol) that are allowed in the value parameter for the parse operation to succeed. styles must be a combination of bit flags from the NumberStyles enumeration. The style parameter makes this method overload useful when value contains the representation of a hexadecimal value, when the number system (decimal or hexadecimal) represented by value is known only at run time, or when you want to disallow white space or a sign symbol in value.

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 style includes NumberStyles.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, and it can appear 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 NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the culture indicated by the provider parameter. The current culture's 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

fractional_digits

exponential_digits
A sequence of digits from 0 through 9. For fractional_digits, only the digit 0 is valid.
, A culture-specific group separator symbol. The group separator symbol 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 designated by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag. Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, a FormatException is thrown.
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.
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 value with digits only (which corresponds to the NumberStyles.None style) always parses successfully. Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in value. The following table indicates how individual NumberStyles members affect the elements that may be present in value.

NumberStyles value Elements permitted in value in addition to digits
None The digits element only.
AllowDecimalPoint The decimal point (.) and fractional-digits elements.
AllowExponent The "e" or "E" character, which indicates exponential notation. along with exponential_digits.
AllowLeadingWhite The ws element at the start of value.
AllowTrailingWhite The ws element at the end of value.
AllowLeadingSign The sign element at the start of value.
AllowTrailingSign The sign element at the end of value.
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.

Unlike the other NumberStyles values, which allow for but do not require the presence of particular style elements in value, the NumberStyles.AllowHexSpecifier style value means that the individual numeric characters in value are always interpreted as hexadecimal characters. Valid hexadecimal characters are 0-9, A-F, and a-f. The only other flags that can be combined with the style parameter are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number 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. Typically, provider can be any one of the following:

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

See also

Applies to

Parse(String, NumberStyles, IFormatProvider)

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

Converts the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent.

public:
 static System::Numerics::BigInteger Parse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static System::Numerics::BigInteger Parse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::Numerics::BigInteger>::Parse;
public static System.Numerics.BigInteger Parse (string value, System.Globalization.NumberStyles style, IFormatProvider provider);
public static System.Numerics.BigInteger Parse (string value, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> System.Numerics.BigInteger
Public Shared Function Parse (value As String, style As NumberStyles, provider As IFormatProvider) As BigInteger

Parameters

value
String

A string that contains a number to convert.

style
NumberStyles

A bitwise combination of the enumeration values that specify the permitted format of value.

provider
IFormatProvider

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

Returns

A value that is equivalent to the number specified in the value parameter.

Implements

Exceptions

style is not a NumberStyles value.

-or-

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

value is null.

value does not comply with the input pattern specified by style.

Examples

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

// Call parse with default values of style and provider
Console.WriteLine(BigInteger.Parse("  -300   ",
                  NumberStyles.Integer, CultureInfo.CurrentCulture));
// Call parse with default values of style and provider supporting tilde as negative sign
Console.WriteLine(BigInteger.Parse("   ~300  ",
                                   NumberStyles.Integer, new BigIntegerFormatProvider()));
// Call parse with only AllowLeadingWhite and AllowTrailingWhite
// Exception thrown because of presence of negative sign
try
{
   Console.WriteLine(BigInteger.Parse("    ~300   ",
                                NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
                                new BigIntegerFormatProvider()));
}
catch (FormatException e)
{
   Console.WriteLine("{0}: \n   {1}", e.GetType().Name, e.Message);
}
// Call parse with only AllowHexSpecifier
// Exception thrown because of presence of negative sign
try
{
   Console.WriteLine(BigInteger.Parse("-3af", NumberStyles.AllowHexSpecifier,
                                      new BigIntegerFormatProvider()));
}
catch (FormatException e)
{
   Console.WriteLine("{0}: \n   {1}", e.GetType().Name, e.Message);
}
// Call parse with only NumberStyles.None
// Exception thrown because of presence of white space and sign
try
{
   Console.WriteLine(BigInteger.Parse(" -300 ", NumberStyles.None,
                                      new BigIntegerFormatProvider()));
}
catch (FormatException e)
{
   Console.WriteLine("{0}: \n   {1}", e.GetType().Name, e.Message);
}
// The example displays the followingoutput:
//       -300
//       -300
//       FormatException:
//          The value could not be parsed.
//       FormatException:
//          The value could not be parsed.
//       FormatException:
//          The value could not be parsed.
    // Call parse with default values of style and provider
    printfn $"""{BigInteger.Parse("  -300   ", NumberStyles.Integer, CultureInfo.CurrentCulture)}"""

    // Call parse with default values of style and provider supporting tilde as negative sign
    printfn $"""{BigInteger.Parse("   ~300  ", NumberStyles.Integer, new BigIntegerFormatProvider())}"""

    // Call parse with only AllowLeadingWhite and AllowTrailingWhite
    // Exception thrown because of presence of negative sign
    try
        printfn
            $"""{BigInteger.Parse(
                     "    ~300   ",
                     NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite,
                     new BigIntegerFormatProvider()
                 )}"""
    with :? FormatException as e ->
        printfn $"{e.GetType().Name}: \n   {e.Message}"

    // Call parse with only AllowHexSpecifier
    // Exception thrown because of presence of negative sign
    try
        printfn $"""{BigInteger.Parse("-3af", NumberStyles.AllowHexSpecifier, new BigIntegerFormatProvider())}"""
    with :? FormatException as e ->
        printfn $"{e.GetType().Name}: \n   {e.Message}"

    // Call parse with only NumberStyles.None
    // Exception thrown because of presence of white space and sign
    try
        printfn $"""{BigInteger.Parse(" -300 ", NumberStyles.None, new BigIntegerFormatProvider())}"""
    with :? FormatException as e ->
        printfn $"{e.GetType().Name}: \n   {e.Message}"
// The example displays the followingoutput:
//       -300
//       -300
//       FormatException:
//          The value could not be parsed.
//       FormatException:
//          The value could not be parsed.
//       FormatException:
//          The value could not be parsed.
' Call parse with default values of style and provider
Console.WriteLine(BigInteger.Parse("  -300   ", _
                  NumberStyles.Integer, CultureInfo.CurrentCulture))
' Call parse with default values of style and provider supporting tilde as negative sign
Console.WriteLine(BigInteger.Parse("   ~300  ", _
                                   NumberStyles.Integer, New BigIntegerFormatProvider()))
' Call parse with only AllowLeadingWhite and AllowTrailingWhite
' Exception thrown because of presence of negative sign
Try
   Console.WriteLIne(BigInteger.Parse("    ~300   ", _
                                      NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite, _
                                      New BigIntegerFormatProvider()))
Catch e As FormatException
   Console.WriteLine("{0}: {1}   {2}", e.GetType().Name, vbCrLf, e.Message)
End Try                                   
' Call parse with only AllowHexSpecifier
' Exception thrown because of presence of negative sign
Try
   Console.WriteLIne(BigInteger.Parse("-3af", NumberStyles.AllowHexSpecifier, _
                                      New BigIntegerFormatProvider()))
Catch e As FormatException
   Console.WriteLine("{0}: {1}   {2}", e.GetType().Name, vbCrLf, e.Message)
End Try                                 
' Call parse with only NumberStyles.None
' Exception thrown because of presence of white space and sign
Try
   Console.WriteLIne(BigInteger.Parse(" -300 ", NumberStyles.None, _
                                      New BigIntegerFormatProvider()))
Catch e As FormatException
   Console.WriteLine("{0}: {1}   {2}", e.GetType().Name, vbCrLf, e.Message)
End Try
' The example displays the following output:
'       -300
'       -300
'       FormatException:
'          The value could not be parsed.
'       FormatException:
'          The value could not be parsed.
'       FormatException:
'          The value could not be parsed.

A number of the individual calls to the Parse(String, NumberStyles, IFormatProvider) 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 = 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 style parameter defines the style elements (such as white space, the positive or negative sign symbol, the group separator symbol, or the decimal point symbol) that are allowed in the value parameter for the parse operation to succeed. styles must be a combination of bit flags from the NumberStyles enumeration. The style parameter makes this method overload useful when value contains the string representation of a hexadecimal value, when the number system (decimal or hexadecimal) represented by value is known only at run time, or when you want to disallow white space or a sign symbol in value.

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 style includes NumberStyles.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, and it can appear 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 NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the culture indicated by the provider parameter. The current culture's 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

fractional_digits

exponential_digits
A sequence of digits from 0 through 9. For fractional_digits, only the digit 0 is valid.
, A culture-specific group separator symbol. The group separator symbol 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 designated by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag. Only the digit 0 can appear as a fractional digit for the parse operation to succeed; if fractional_digits includes any other digit, a FormatException is thrown.
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.
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 digits only (which corresponds to the NumberStyles.None style) always parses successfully. Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in the input string. The following table indicates how individual NumberStyles members affect the elements that may be present in value.

NumberStyles value Elements permitted in value in addition to digits
None The digits element only.
AllowDecimalPoint The decimal point (.) and fractional-digits elements.
AllowExponent The "e" or "E" character, which indicates exponential notation. along with exponential_digits.
AllowLeadingWhite The ws element at the start of value.
AllowTrailingWhite The ws element at the end of value.
AllowLeadingSign The sign element at the start of value.
AllowTrailingSign The sign element at the end of value.
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 Parse 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 Parse method to restore the BigInteger value.

Unlike the other NumberStyles values, which allow for but do not require the presence of particular style elements in value, the NumberStyles.AllowHexSpecifier style value means that the individual numeric characters in value are always interpreted as hexadecimal characters. Valid hexadecimal characters are 0-9, A-F, and a-f. The only other flags that can be combined with the style parameter are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number 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 Parse(String, NumberStyles) 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" };
      foreach (string hexString in hexStrings)
      {
         BigInteger number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier);
         Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
      }
   }
}
// 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
    let number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier)
    printfn $"Converted 0x{hexString} to {number:N0}."
// 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" }
      For Each hexString As String In hexStrings
         Dim number As BigInteger = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier)
         Console.WriteLine("Converted 0x{0} to {1}.", hexString, number)
      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. Typically, provider can be any one of the following:

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

See also

Applies to