Επεξεργασία

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


Int32.Parse Method

Definition

Converts the string representation of a number to its 32-bit signed integer equivalent.

Overloads

Parse(String)

Converts the string representation of a number to its 32-bit signed integer equivalent.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Parses a span of UTF-8 characters into a value.

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 32-bit signed integer equivalent.

Parse(String, IFormatProvider)

Converts the string representation of a number in a specified culture-specific format to its 32-bit signed integer equivalent.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Parses a span of UTF-8 characters into a value.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

Parse(String, NumberStyles, IFormatProvider)

Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

Parse(String)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Converts the string representation of a number to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s);
public static int Parse (string s);
static member Parse : string -> int
Public Shared Function Parse (s As String) As Integer

Parameters

s
String

A string containing a number to convert.

Returns

A 32-bit signed integer equivalent to the number contained in s.

Exceptions

s is not in the correct format.

s represents a number less than Int32.MinValue or greater than Int32.MaxValue.

Examples

The following example demonstrates how to convert a string value into a 32-bit signed integer value using the Int32.Parse(String) method. The resulting integer value is then displayed to the console.

using namespace System;

void main()
{
   array<String^>^ values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                              "0xFA1B", "163042", "-10", "007", "2147483647", 
                              "2147483648", "16e07", "134985.0", "-12034",
                              "-2147483648", "-2147483649" };
   for each (String^ value in values)
   {
      try {
         Int32 number = Int32::Parse(value); 
         Console::WriteLine("{0} --> {1}", value, number);
      }
      catch (FormatException^ e) {
         Console::WriteLine("{0}: Bad Format", value);
      }   
      catch (OverflowException^ e) {
         Console::WriteLine("{0}: Overflow", value);   
      }  
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                          "0xFA1B", "163042", "-10", "007", "2147483647",
                          "2147483648", "16e07", "134985.0", "-12034",
                          "-2147483648", "-2147483649" };
      foreach (string value in values)
      {
         try {
            int number = Int32.Parse(value);
            Console.WriteLine("{0} --> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("{0}: Bad Format", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0}: Overflow", value);
         }
      }
   }
}
// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
open System

let values =
    [ "+13230"; "-0"; "1,390,146"; "$190,235,421,127"
      "0xFA1B"; "163042"; "-10"; "007"; "2147483647"
      "2147483648"; "16e07"; "134985.0"; "-12034"
      "-2147483648"; "-2147483649" ]

for value in values do
    try
        let number = Int32.Parse value
        printfn $"{value} --> {number}"
    with 
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"
    

// The example displays the following output:
//       +13230 --> 13230
//       -0 --> 0
//       1,390,146: Bad Format
//       $190,235,421,127: Bad Format
//       0xFA1B: Bad Format
//       163042 --> 163042
//       -10 --> -10
//       007 --> 7
//       2147483647 --> 2147483647
//       2147483648: Overflow
//       16e07: Bad Format
//       134985.0: Bad Format
//       -12034 --> -12034
//       -2147483648 --> -2147483648
//       -2147483649: Overflow
Module Example
   Public Sub Main()
      Dim values() As String = { "+13230", "-0", "1,390,146", "$190,235,421,127",
                                 "0xFA1B", "163042", "-10", "007", "2147483647", 
                                 "2147483648", "16e07", "134985.0", "-12034",
                                 "-2147483648", "-2147483649"  }
      For Each value As String In values
         Try
            Dim number As Integer = Int32.Parse(value) 
            Console.WriteLine("{0} --> {1}", value, number)
         Catch e As FormatException
            Console.WriteLine("{0}: Bad Format", value)
         Catch e As OverflowException
            Console.WriteLine("{0}: Overflow", value)   
         End Try  
      Next
   End Sub
End Module
' The example displays the following output:
'       +13230 --> 13230
'       -0 --> 0
'       1,390,146: Bad Format
'       $190,235,421,127: Bad Format
'       0xFA1B: Bad Format
'       163042 --> 163042
'       -10 --> -10
'       007 --> 7
'       2147483647 --> 2147483647
'       2147483648: Overflow
'       16e07: Bad Format
'       134985.0: Bad Format
'       -12034 --> -12034
'       -2147483648 --> -2147483648
'       -2147483649: Overflow

Remarks

The s parameter contains a number of the form:

[ws][sign]digits[ws]

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

Element Description
ws Optional white space.
sign An optional sign.
digits A sequence of digits ranging from 0 to 9.

The s parameter is interpreted using the NumberStyles.Integer style. In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. To explicitly define the style elements that can be present in s, use either the Int32.Parse(String, NumberStyles) or the Int32.Parse(String, NumberStyles, IFormatProvider) method.

The s parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture. For more information, see CurrentInfo. To parse a string using the formatting information of some other culture, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.

See also

Applies to

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs

Parses a span of UTF-8 characters into a value.

public:
 static int Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<int>::Parse;
public static int Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Integer

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

provider
IFormatProvider

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

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Parses a span of characters into a value.

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

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:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Converts the string representation of a number in a specified style to its 32-bit signed integer equivalent.

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

Parameters

s
String

A string containing a number to convert.

style
NumberStyles

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

Returns

A 32-bit signed integer equivalent to the number specified in s.

Exceptions

style is not a NumberStyles value.

-or-

style is not a combination of AllowHexSpecifier and HexNumber values.

s is not in a format compliant with style.

s represents a number less than Int32.MinValue or greater than Int32.MaxValue.

-or-

s includes non-zero, fractional digits.

Examples

The following example uses the Int32.Parse(String, NumberStyles) method to parse the string representations of several Int32 values. The current culture for the example is en-US.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("104.0", NumberStyles::AllowDecimalPoint);
      Convert("104.9", NumberStyles::AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles::AllowCurrencySymbol |
                                 NumberStyles::Number);
      Convert("103E06", NumberStyles::AllowExponent);
      Convert("-1,345,791", NumberStyles::AllowThousands);
      Convert("(1,345,791)", NumberStyles::AllowThousands |
                             NumberStyles::AllowParentheses);
   }

private:
   static void Convert(String^ value, NumberStyles style)
   {
      try
      {
         int number = Int32::Parse(value, style);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
};

int main()
{
    ParseInt32::Main();
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("104.0", NumberStyles.AllowDecimalPoint);
      Convert("104.9", NumberStyles.AllowDecimalPoint);
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol |
                                 NumberStyles.Number);
      Convert("103E06", NumberStyles.AllowExponent);
      Convert("-1,345,791", NumberStyles.AllowThousands);
      Convert("(1,345,791)", NumberStyles.AllowThousands |
                             NumberStyles.AllowParentheses);
   }

   private static void Convert(string value, NumberStyles style)
   {
      try
      {
         int number = Int32.Parse(value, style);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
open System
open System.Globalization

let convert value (style: NumberStyles) =
    try
        let number = Int32.Parse(value, style)
        printfn $"Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"Unable to convert '{value}'."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the Int32 type."

convert "104.0" NumberStyles.AllowDecimalPoint
convert "104.9" NumberStyles.AllowDecimalPoint
convert " $17,198,064.42" (NumberStyles.AllowCurrencySymbol ||| NumberStyles.Number)
convert "103E06" NumberStyles.AllowExponent
convert "-1,345,791" NumberStyles.AllowThousands
convert "(1,345,791)" (NumberStyles.AllowThousands ||| NumberStyles.AllowParentheses)


// The example displays the following output to the console:
//       Converted '104.0' to 104.
//       '104.9' is out of range of the Int32 type.
//       ' $17,198,064.42' is out of range of the Int32 type.
//       Converted '103E06' to 103000000.
//       Unable to convert '-1,345,791'.
//       Converted '(1,345,791)' to -1345791.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("104.0", NumberStyles.AllowDecimalPoint)    
      Convert("104.9", NumberStyles.AllowDecimalPoint)
      Convert(" $17,198,064.42", NumberStyles.AllowCurrencySymbol Or _
                                 NumberStyles.Number)
      Convert("103E06", NumberStyles.AllowExponent)  
      Convert("-1,345,791", NumberStyles.AllowThousands)
      Convert("(1,345,791)", NumberStyles.AllowThousands Or _
                             NumberStyles.AllowParentheses)
   End Sub
   
   Private Sub Convert(value As String, style As NumberStyles)
      Try
         Dim number As Integer = Int32.Parse(value, style)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '104.0' to 104.
'       '104.9' is out of range of the Int32 type.
'       ' $17,198,064.42' is out of range of the Int32 type.
'       Converted '103E06' to 103000000.
'       Unable to convert '-1,345,791'.
'       Converted '(1,345,791)' to -1345791.

Remarks

The style parameter defines the style elements (such as white space, the positive or negative sign symbol, or the thousands separator symbol) that are allowed in the s 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 s parameter may include the following elements:

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

Or, if style includes AllowHexSpecifier:

[ws]hexdigits[ws]

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

Element Description
ws Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s 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 s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s 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 thousands separator symbol. The current culture's thousands separator can appear in s if style includes the NumberStyles.AllowThousands flag.
. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s 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, an OverflowException is thrown.
e The 'e' or 'E' character, which indicates that the value is represented in exponential notation. The s 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 successfull if it is in the range of the Int32 type. Most of the remaining NumberStyles members control elements that may be 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 s.

NumberStyles value Elements permitted in s in addition to digits
None The digits element only.
AllowDecimalPoint The decimal point ( . ) and fractional-digits elements.
AllowExponent The s parameter can also use exponential notation.
AllowLeadingWhite The ws element at the beginning of s.
AllowTrailingWhite The ws element at the end of s.
AllowLeadingSign The sign element at the beginning of s.
AllowTrailingSign The sign element at the end of s.
AllowParentheses The sign element in the form of parentheses enclosing the numeric value.
AllowThousands The thousands separator ( , ) element.
AllowCurrencySymbol The $ element.
Currency All. The s parameter cannot represent a hexadecimal number or a number in exponential notation.
Float The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point ( . ) symbol. The s parameter can also use exponential notation.
Number The ws, sign, thousands separator ( , ), and decimal point ( . ) elements.
Any All styles, except s cannot represent a hexadecimal number.

If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value without a prefix. For example, "C9AF3" parses successfully, but "0xC9AF3" does not. The only other flags that can be combined with the s parameter it are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number style, NumberStyles.HexNumber, that includes both white space flags.)

The s parameter is parsed 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 Int32.Parse(String, NumberStyles, IFormatProvider) overload.

See also

Applies to

Parse(String, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Converts the string representation of a number in a specified culture-specific format to its 32-bit signed integer equivalent.

public:
 static int Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static int Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<int>::Parse;
public static int Parse (string s, IFormatProvider provider);
public static int Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> int
Public Shared Function Parse (s As String, provider As IFormatProvider) As Integer

Parameters

s
String

A string containing a number to convert.

provider
IFormatProvider

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

Returns

A 32-bit signed integer equivalent to the number specified in s.

Implements

Exceptions

s is not of the correct format.

s represents a number less than Int32.MinValue or greater than Int32.MaxValue.

Examples

The following example is the button click event handler of a Web form. It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. It then instantiates a CultureInfo object that corresponds to that locale. The NumberFormatInfo object that belongs to that CultureInfo object is then passed to the Parse(String, IFormatProvider) method to convert the user's input to an Int32 value.

protected void OkToInteger_Click(object sender, EventArgs e)
{
    string locale;
    int number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = Int32.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (Exception)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToInteger_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToInteger.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Integer

   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub

   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub

   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)

   ' Convert user input from a string to a number
   Try
      number = Int32.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

Remarks

This overload of the Parse(String, IFormatProvider) method is typically used to convert text that can be formatted in a variety of ways to an Int32 value. For example, it can be used to convert the text entered by a user into an HTML text box to a numeric value.

The s parameter contains a number of the form:

[ws][sign]digits[ws]

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

Element Description
ws Optional white space.
sign An optional sign.
digits A sequence of digits ranging from 0 to 9.

The s parameter is interpreted using the NumberStyles.Integer style. In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. To explicitly define the style elements that can be present in s, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.

The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information about the format of s. If provider is null, the NumberFormatInfo object for the current culture is used.

See also

Applies to

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs

Parses a span of UTF-8 characters into a value.

public static int Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> int
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

style
NumberStyles

A bitwise combination of number styles that can be present in utf8Text.

provider
IFormatProvider

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

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

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

Parameters

s
ReadOnlySpan<Char>

A span containing the characters representing the number to convert.

style
NumberStyles

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

provider
IFormatProvider

An object that supplies culture-specific information about the format of s.

Returns

A 32-bit signed integer equivalent to the number specified in s.

Implements

Applies to

Parse(String, NumberStyles, IFormatProvider)

Source:
Int32.cs
Source:
Int32.cs
Source:
Int32.cs

Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent.

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

Parameters

s
String

A string containing a number to convert.

style
NumberStyles

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

provider
IFormatProvider

An object that supplies culture-specific information about the format of s.

Returns

A 32-bit signed integer equivalent to the number specified in s.

Implements

Exceptions

style is not a NumberStyles value.

-or-

style is not a combination of AllowHexSpecifier and HexNumber values.

s is not in a format compliant with style.

s represents a number less than Int32.MinValue or greater than Int32.MaxValue.

-or-

s includes non-zero, fractional digits.

Examples

The following example uses a variety of style and provider parameters to parse the string representations of Int32 values. It also illustrates some of the different ways the same string can be interpreted depending on the culture whose formatting information is used for the parsing operation.

using namespace System;
using namespace System::Globalization;

public ref class ParseInt32
{
public:
   static void Main()
   {
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands, 
              gcnew CultureInfo("en-GB"));
      Convert("12,000", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles::Float, gcnew CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles::Float | NumberStyles::AllowThousands,
              gcnew CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles::Float | NumberStyles::AllowThousands,
              NumberFormatInfo::InvariantInfo);
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint, 
              gcnew CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowDecimalPoint,
              gcnew CultureInfo("en-US"));
      Convert("631,900", NumberStyles::Integer | NumberStyles::AllowThousands,
              gcnew CultureInfo("en-US"));
   }

private:
   static void Convert(String^ value, NumberStyles style,
                               IFormatProvider^ provider)
   {
      try
      {
         int number = Int32::Parse(value, style, provider);
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException^)
      {
         Console::WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException^)
      {
         Console::WriteLine("'{0}' is out of range of the Int32 type.", value);   
      }
   }                               
};

int main()
{
    ParseInt32::Main();
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
using System;
using System.Globalization;

public class ParseInt32
{
   public static void Main()
   {
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("en-GB"));
      Convert("12,000", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("fr-FR"));
      Convert("12,000", NumberStyles.Float, new CultureInfo("en-US"));

      Convert("12 425,00", NumberStyles.Float | NumberStyles.AllowThousands,
              new CultureInfo("sv-SE"));
      Convert("12,425.00", NumberStyles.Float | NumberStyles.AllowThousands,
              NumberFormatInfo.InvariantInfo);
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("fr-FR"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowDecimalPoint,
              new CultureInfo("en-US"));
      Convert("631,900", NumberStyles.Integer | NumberStyles.AllowThousands,
              new CultureInfo("en-US"));
   }

   private static void Convert(string value, NumberStyles style,
                               IFormatProvider provider)
   {
      try
      {
         int number = Int32.Parse(value, style, provider);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value);
      }
   }
}
// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
open System
open System.Globalization

let convert (value: string) (style: NumberStyles) (provider: IFormatProvider) =
    try
        let number = Int32.Parse(value, style, provider)
        printfn $"Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"Unable to convert '{value}'."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the Int32 type."

convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "en-GB")
convert "12,000" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "fr-FR")
convert "12,000" NumberStyles.Float (CultureInfo "en-US")
convert "12 425,00" (NumberStyles.Float ||| NumberStyles.AllowThousands) (CultureInfo "sv-SE")
convert "12,425.00" (NumberStyles.Float ||| NumberStyles.AllowThousands) NumberFormatInfo.InvariantInfo
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "fr-FR")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint) (CultureInfo "en-US")
convert "631,900" (NumberStyles.Integer ||| NumberStyles.AllowThousands) (CultureInfo "en-US")

// This example displays the following output to the console:
//       Converted '12,000' to 12000.
//       Converted '12,000' to 12.
//       Unable to convert '12,000'.
//       Converted '12 425,00' to 12425.
//       Converted '12,425.00' to 12425.
//       '631,900' is out of range of the Int32 type.
//       Unable to convert '631,900'.
//       Converted '631,900' to 631900.
Imports System.Globalization

Module ParseInt32
   Public Sub Main()
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("en-GB"))      
      Convert("12,000", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("fr-FR"))
      Convert("12,000", NumberStyles.Float, New CultureInfo("en-US"))
      
      Convert("12 425,00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              New CultureInfo("sv-SE")) 
      Convert("12,425.00", NumberStyles.Float Or NumberStyles.AllowThousands, _
              NumberFormatInfo.InvariantInfo) 
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _ 
              New CultureInfo("fr-FR"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowDecimalPoint, _
              New CultureInfo("en-US"))
      Convert("631,900", NumberStyles.Integer Or NumberStyles.AllowThousands, _
              New CultureInfo("en-US"))
   End Sub

   Private Sub Convert(value As String, style As NumberStyles, _
                       provider As IFormatProvider)
      Try
         Dim number As Integer = Int32.Parse(value, style, provider)
         Console.WriteLine("Converted '{0}' to {1}.", value, number)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", value)
      Catch e As OverflowException
         Console.WriteLine("'{0}' is out of range of the Int32 type.", value)   
      End Try
   End Sub                       
End Module
' This example displays the following output to the console:
'       Converted '12,000' to 12000.
'       Converted '12,000' to 12.
'       Unable to convert '12,000'.
'       Converted '12 425,00' to 12425.
'       Converted '12,425.00' to 12425.
'       '631,900' is out of range of the Int32 type.
'       Unable to convert '631,900'.
'       Converted '631,900' to 631900.

Remarks

The style parameter defines the style elements (such as white space or the positive sign) that are allowed in the s 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 s parameter may include the following elements:

[ws][$][sign][digits,]digits[.fractional_digist][e[sign]exponential_digits][ws]

Or, if style includes AllowHexSpecifier:

[ws]hexdigits[ws]

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

Element Description
ws Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag or at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s 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 thousands separator symbol. The thousands separator of the culture specified by provider can appear in s 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 s 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, an OverflowException is thrown.
e The 'e' or 'E' character, which indicates that the value is represented in exponential notation. The s 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 style) always parses successfully if it is in the range of the Int32 type. Most of the remaining NumberStyles members control elements that may be 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 s.

Non-composite NumberStyles values Elements permitted in s in addition to digits
NumberStyles.None Decimal digits only.
NumberStyles.AllowDecimalPoint The decimal point ( . ) and fractional-digits elements. However, fractional-digits must consist of only one or more 0 digits or an OverflowException is thrown.
NumberStyles.AllowExponent The s parameter can also use exponential notation. If s represents a number in exponential notation, it must represent an integer within the range of the Int32 data type without a non-zero, fractional component.
NumberStyles.AllowLeadingWhite The ws element at the beginning of s.
NumberStyles.AllowTrailingWhite The ws element at the end of s.
NumberStyles.AllowLeadingSign A positive sign can appear before digits.
NumberStyles.AllowTrailingSign A positive sign can appear after digits.
NumberStyles.AllowParentheses The sign element in the form of parentheses enclosing the numeric value.
NumberStyles.AllowThousands The thousands separator ( , ) element.
NumberStyles.AllowCurrencySymbol The $ element.

If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value without a prefix. For example, "C9AF3" parses successfully, but "0xC9AF3" does not. The only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration has a composite number style, NumberStyles.HexNumber, that includes both white space flags.)

The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information used in parsing. If provider is null, the NumberFormatInfo object for the current culture is used.

See also

Applies to