Int32.Parse メソッド

定義

数値の文字列形式を、それと等価な 32 ビット符号付き整数に変換します。

オーバーロード

Parse(String, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャに固有の書式による数値の文字列形式を、それと等価の 32 ビット符号付き整数に変換します。

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャに固有の書式による数値のスパン表現を、等価の 32 ビット符号付き整数に変換します。

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

Parse(String, IFormatProvider)

指定したカルチャに固有の書式による数値の文字列形式を、それと等価な 32 ビット符号付き整数に変換します。

Parse(String)

数値の文字列形式を、それと等価な 32 ビット符号付き整数に変換します。

Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

Parse(ReadOnlySpan<Byte>, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

Parse(String, NumberStyles)

指定したスタイルの数値の文字列形式を、それと等しい 32 ビット符号付き整数に変換します。

Parse(String, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャに固有の書式による数値の文字列形式を、それと等価の 32 ビット符号付き整数に変換します。

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

パラメーター

s
String

変換する数値を含む文字列。

style
NumberStyles

s で存在する可能性を持つスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、Integer です。

provider
IFormatProvider

s の書式設定に関するカルチャ固有の情報を提供するオブジェクト。

戻り値

s で指定した数値と等しい 32 ビット符号付き整数。

実装

例外

snullです。

styleNumberStyles 値ではありません。

- または -

styleAllowHexSpecifier 値と HexNumber 値の組み合わせではありません。

s の形式が style に準拠していません。

s は、 Int32.MinValue より小さい数値または Int32.MaxValue より大きい数値を表します。

- または -

s に 0 以外の小数部の桁が含まれています。

次の例では、さまざまな style パラメーターと provider パラメーターを使用して、値の Int32 文字列表現を解析します。 また、解析操作に書式設定情報が使用されるカルチャに応じて、同じ文字列を解釈できるさまざまな方法についても説明します。

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.

注釈

パラメーターは style 、解析操作を成功させるために パラメーターで s 許可されるスタイル要素 (空白や正符号など) を定義します。 列挙からのビット フラグ NumberStyles の組み合わせである必要があります。 の style値によっては、パラメーターに s 次の要素が含まれる場合があります。

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

または、 が含まれているAllowHexSpecifier場合styleは 。

[ws]hexdigits[ws]

角かっこ ([ と ]) の項目は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws オプションの空白。 空白は、 フラグを含む場合は のs先頭に表示でき、フラグが含NumberStyles.AllowLeadingWhiteまれている場合styleは のs末尾にNumberStyles.AllowTrailingWhite表示styleできます。
$ カルチャ固有の通貨記号。 文字列内の位置は、 パラメーターの NumberFormatInfo.CurrencyPositivePatternNumberFormatInfo メソッドによって返される オブジェクトの provider プロパティによってGetFormat定義されます。 フラグが含まれている場合styleは、通貨記号を にsNumberStyles.AllowCurrencySymbol表示できます。
sign 省略可能な記号。 フラグが含まれている場合は のs先頭に、フラグがNumberStyles.AllowLeadingSign含まれている場合styleは のs末尾にNumberStyles.AllowTrailingSign表示styleされます。 に フラグが含まれている場合style、かっこを使用sして負の値をNumberStyles.AllowParentheses示すことができます。
数値

fractional_digits

exponential_digits
0 ~ 9 の数字のシーケンス。 fractional_digitsの場合、数字 0 のみが有効です。
, カルチャ固有の桁区切り記号。 で指定されたproviderカルチャの桁区切り記号は、 フラグが含まれている場合styleに にsNumberStyles.AllowThousands表示できます。
. カルチャ固有の小数点記号。 で指定されたproviderカルチャの小数点記号は、 フラグが含まれている場合styleに にsNumberStyles.AllowDecimalPoint表示できます。

解析操作を成功させるために小数部の数字として表示できるのは、数字 0 だけです。fractional_digitsに他 数字が含まれている場合は、 OverflowException がスローされます。
e 値が指数表記で表されることを示す 'e' または 'E' 文字。 フラグが含まれている場合style、パラメーターはs指数表記で数値をNumberStyles.AllowExponent表すことができます。
hexdigits 0 から f、または 0 から F までの 16 進数のシーケンス。

注意

の終端 NUL (U+0000) 文字 s は、引数の style 値に関係なく、解析操作では無視されます。

10 進数のみの文字列 (スタイルに NumberStyles.None 対応) は、型の Int32 範囲内にある場合は常に正常に解析されます。 残りの NumberStyles メンバーのほとんどは、この入力文字列に存在する必要がない要素を制御します。 次の表は、 にs存在する可能性がある要素に個々NumberStylesのメンバーがどのように影響するかを示しています。

非複合 NumberStyles 値 数字に加えて、 で許可される要素
NumberStyles.None 10 進数のみ。
NumberStyles.AllowDecimalPoint 小数点 ( . ) と 小数部の要素 。 ただし、 小数部の数字 は 1 つ以上の 0 桁のみで構成する必要があります。または、 OverflowException がスローされます。
NumberStyles.AllowExponent パラメーターでは s 指数表記を使用することもできます。 指数表記で数値を表す場合 s は、0 以外の小数部を含まないデータ型の範囲内の Int32 整数を表す必要があります。
NumberStyles.AllowLeadingWhite の先頭sにある ws 要素。
NumberStyles.AllowTrailingWhite の末尾sにある ws 要素。
NumberStyles.AllowLeadingSign 正符号は 数字の前に表示できます。
NumberStyles.AllowTrailingSign 正符号は 数字の後に表示できます。
NumberStyles.AllowParentheses 数値を囲むかっこの形式の 符号 要素。
NumberStyles.AllowThousands 桁区切り記号 ( ) 要素。
NumberStyles.AllowCurrencySymbol $ 要素。

フラグを使用する NumberStyles.AllowHexSpecifier 場合は、 s プレフィックスのない 16 進数の値にする必要があります。 たとえば、"C9AF3" は正常に解析されますが、"0xC9AF3" は解析されません。 に存在できるその他の style フラグは NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteだけです。 (列挙体 NumberStyles には、 NumberStyles.HexNumber両方の空白フラグを含む複合数値スタイル があります)。

パラメーターはproviderIFormatProviderCultureInfo オブジェクトなどのNumberFormatInfo実装です。 パラメーターは provider 、解析で使用されるカルチャ固有の情報を提供します。 が のnull場合provider、現在のNumberFormatInfoカルチャの オブジェクトが使用されます。

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャに固有の書式による数値のスパン表現を、等価の 32 ビット符号付き整数に変換します。

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

パラメーター

s
ReadOnlySpan<Char>

変換する数値を表す文字を格納しているスパン。

style
NumberStyles

s で存在する可能性を持つスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、Integer です。

provider
IFormatProvider

s の書式設定に関するカルチャ固有の情報を提供するオブジェクト。

戻り値

s で指定した数値と等しい 32 ビット符号付き整数。

実装

適用対象

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

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

パラメーター

utf8Text
ReadOnlySpan<Byte>

解析する UTF-8 文字のスパン。

style
NumberStyles

utf8Text存在できる数値スタイルのビットごとの組み合わせ。

provider
IFormatProvider

utf8Text に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した utf8Text結果。

実装

適用対象

Parse(String, IFormatProvider)

指定したカルチャに固有の書式による数値の文字列形式を、それと等価な 32 ビット符号付き整数に変換します。

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

パラメーター

s
String

変換する数値を含む文字列。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

s で指定した数値と等しい 32 ビット符号付き整数。

実装

例外

snullです。

s が正しい形式ではありません。

s は、 Int32.MinValue より小さい数値または Int32.MaxValue より大きい数値を表します。

次の例は、Web フォームのボタン クリック イベント ハンドラーです。 プロパティによって返される配列を HttpRequest.UserLanguages 使用して、ユーザーのロケールを決定します。 その後、そのロケールに CultureInfo 対応する オブジェクトをインスタンス化します。 NumberFormatInfoそのCultureInfoオブジェクトに属する オブジェクトは、 メソッドにParse(String, IFormatProvider)渡され、ユーザーの入力を値にInt32変換します。

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

注釈

メソッドの Parse(String, IFormatProvider) このオーバーロードは、通常、さまざまな方法で書式設定できるテキストを値に変換するために Int32 使用されます。 たとえば、ユーザーが入力したテキストを HTML テキスト ボックスに数値に変換するために使用できます。

パラメーターには s 、次の形式の数値が含まれています。

[ws][sign]digits[ws]

角かっこ ([ と ]) の項目は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws オプションの空白。
sign 省略可能な記号。
数値 0 から 9 までの数字のシーケンス。

パラメーターは s 、 スタイルを使用して NumberStyles.Integer 解釈されます。 10 進数に加えて、先頭と末尾のスペースと先頭の記号のみを使用できます。 に存在できるスタイル要素を明示的に s定義するには、 メソッドを使用します Int32.Parse(String, NumberStyles, IFormatProvider)

パラメーターはproviderIFormatProviderCultureInfo オブジェクトなどのNumberFormatInfo実装です。 パラメーターは provider 、 の形式に関するカルチャ固有の s情報を提供します。 が のnull場合provider、現在のNumberFormatInfoカルチャの オブジェクトが使用されます。

こちらもご覧ください

適用対象

Parse(String)

数値の文字列形式を、それと等価な 32 ビット符号付き整数に変換します。

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

パラメーター

s
String

変換する数値を含む文字列。

戻り値

s に格納されている数値と等しい 32 ビット符号付き整数。

例外

snullです。

s が正しい形式ではありません。

s は、 Int32.MinValue より小さい数値または Int32.MaxValue より大きい数値を表します。

次の例では、 メソッドを使用して文字列値を 32 ビット符号付き整数値に変換する方法を Int32.Parse(String) 示します。 その後、結果の整数値がコンソールに表示されます。

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

注釈

パラメーターには s 、次の形式の数値が含まれています。

[ws][sign]digits[ws]

角かっこ ([ と ]) の項目は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws オプションの空白。
sign 省略可能な記号。
数値 0 から 9 までの数字のシーケンス。

パラメーターは s 、 スタイルを使用して NumberStyles.Integer 解釈されます。 10 進数に加えて、先頭と末尾のスペースと先頭の記号のみを使用できます。 に存在できるスタイル要素を明示的に s定義するには、 Int32.Parse(String, NumberStyles) メソッドまたは メソッドを Int32.Parse(String, NumberStyles, IFormatProvider) 使用します。

パラメーターは s 、現在のシステム カルチャ用に初期化されたオブジェクトの NumberFormatInfo 書式設定情報を使用して解析されます。 詳細については、「CurrentInfo」を参照してください。 他のカルチャの書式設定情報を使用して文字列を解析するには、 メソッドを使用します Int32.Parse(String, NumberStyles, IFormatProvider)

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

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

パラメーター

s
ReadOnlySpan<Char>

解析する文字のスパン。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した s結果。

実装

適用対象

Parse(ReadOnlySpan<Byte>, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

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

パラメーター

utf8Text
ReadOnlySpan<Byte>

解析する UTF-8 文字のスパン。

provider
IFormatProvider

utf8Text に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した utf8Text結果。

実装

適用対象

Parse(String, NumberStyles)

指定したスタイルの数値の文字列形式を、それと等しい 32 ビット符号付き整数に変換します。

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

パラメーター

s
String

変換する数値を含む文字列。

style
NumberStyles

s で使用可能なスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、Integer です。

戻り値

s で指定した数値と等しい 32 ビット符号付き整数。

例外

snullです。

styleNumberStyles 値ではありません。

- または -

styleAllowHexSpecifier 値と HexNumber 値の組み合わせではありません。

s の形式が style に準拠していません。

s は、 Int32.MinValue より小さい数値または Int32.MaxValue より大きい数値を表します。

- または -

s に 0 以外の小数部の桁が含まれています。

次の例では、 メソッドを Int32.Parse(String, NumberStyles) 使用して、複数 Int32 の値の文字列表現を解析します。 この例の現在のカルチャは 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.

注釈

パラメーターは style 、解析操作を成功させるためにパラメーターで s 許可されるスタイル要素 (空白、正または負の記号、桁区切り記号など) を定義します。 列挙からのビット フラグ NumberStyles の組み合わせである必要があります。 の style値によっては、パラメーターに s 次の要素が含まれる場合があります。

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

または、 が含まれているAllowHexSpecifier場合styleは 。

[ws]hexdigits[ws]

角かっこ ([ と ]) の項目は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws オプションの空白。 空白は、 フラグを含む場合は のs先頭に表示され、フラグが含NumberStyles.AllowLeadingWhiteまれている場合styleは のs末尾にNumberStyles.AllowTrailingWhite表示styleされます。
$ カルチャ固有の通貨記号。 文字列内での位置は、現在のカルチャの NumberFormatInfo.CurrencyNegativePattern プロパティと NumberFormatInfo.CurrencyPositivePattern プロパティによって定義されます。 に フラグが含まれている場合styleは、現在のカルチャの通貨記号を NumberStyles.AllowCurrencySymbols表示できます。
sign 省略可能な記号。 署名は、 フラグを含む場合は のs先頭に表示され、フラグが含NumberStyles.AllowLeadingSignまれている場合styleは のs末尾にNumberStyles.AllowTrailingSign表示styleされます。 に フラグが含まれている場合styleは、かっこを使用sして負の値をNumberStyles.AllowParentheses示すことができます。
数値

fractional_digits

exponential_digits
0 から 9 までの数字のシーケンス。 fractional_digitsの場合、数字 0 のみが有効です。
, カルチャ固有の桁区切り記号。 現在のカルチャの桁区切り記号は、 に フラグが含まれている場合stylesNumberStyles.AllowThousands表示できます。
. カルチャ固有の小数点記号。 に フラグが含まれている場合styleは、現在のカルチャの小数点記号を NumberStyles.AllowDecimalPoints表示できます。 解析操作を成功させるために小数部の数字として表示できるのは、数字 0 のみです。 fractional_digits に他の数字が含まれている場合は、 OverflowException がスローされます。
e 値が指数表記で表されることを示す 'e' または 'E' 文字。 フラグが含まれている場合style、パラメーターはs指数表記で数値をNumberStyles.AllowExponent表すことができます。
hexdigits 0 から f、または 0 から F までの 16 進数のシーケンス。

Note

の終端の NUL (U+0000) 文字 s は、引数の style 値に関係なく、解析操作では無視されます。

数字のみの文字列 (スタイルに NumberStyles.None 対応) は、型の範囲内にある場合は常に正常に Int32 解析されます。 残りの NumberStyles メンバーのほとんどは、入力文字列に存在する必要がない要素を制御します。 次の表は、 に存在する可能性がある要素に対する個々 NumberStyles のメンバーの s影響を示しています。

NumberStyles 値 数字に加えて、 で許可される要素
None digits 要素のみ。
AllowDecimalPoint 小数点 ( . ) および 小数部の要素
AllowExponent パラメーターでは s 、指数表記を使用することもできます。
AllowLeadingWhite の先頭sにある ws 要素。
AllowTrailingWhite の末尾sにある ws 要素。
AllowLeadingSign の先頭sにある sign 要素。
AllowTrailingSign の末尾sにある sign 要素。
AllowParentheses 数値を囲むかっこの形式の sign 要素。
AllowThousands 桁区切り記号 ( ) 要素。
AllowCurrencySymbol $ 要素。
Currency すべて。 パラメーターは s 、指数表記で 16 進数または数値を表すことはできません。
Float の先頭または末尾の sws 要素、の先頭s符号、および小数点 ( . ) 記号。 パラメーターでは s 、指数表記を使用することもできます。
Number wssign、桁区切り記号 ( )、および小数点 ( . ) 要素。
Any を除く s すべてのスタイルは、16 進数を表すことはできません。

フラグを使用する NumberStyles.AllowHexSpecifier 場合は、 s プレフィックスのない 16 進値を指定する必要があります。 たとえば、"C9AF3" は正常に解析されますが、"0xC9AF3" では解析されません。 パラメーターとNumberStyles.AllowTrailingWhite組み合わせることができる他のsフラグは NumberStyles.AllowLeadingWhite と のみです。 (列挙には NumberStylesNumberStyles.HexNumber両方の空白フラグを含む複合数値スタイル が含まれています)。

パラメーターは s 、現在のシステム カルチャ用に初期化された オブジェクトの NumberFormatInfo 書式設定情報を使用して解析されます。 解析操作に書式設定情報を使用するカルチャを指定するには、 オーバーロードを Int32.Parse(String, NumberStyles, IFormatProvider) 呼び出します。

こちらもご覧ください

適用対象