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)

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

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 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비트 부호 있는 정수입니다.

구현

예외

s이(가) null인 경우

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifierHexNumber 값의 조합이 아닙니다.

sstyle 규격 형식이 아닙니다.

sInt32.MinValue 보다 작거나 Int32.MaxValue보다 큰 숫자를 나타냅니다.

또는

s에 0이 아닌 소수 자릿수가 포함되어 있습니다.

예제

다음 예제에서는 다양한 styleprovider 매개 변수를 사용하여 값의 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] [$] [기호] [digits,]digits[.fractional_digist][e[sign]exponential_digits][ws]

또는 가 포함된 경우 style 입니다 AllowHexSpecifier.

[ws]hexdigits[ws]

대괄호([ 및 ])의 항목은 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 설명
ws 선택적 공백입니다. 플래그를 포함하는 경우 style 의 시작 부분에 s 공백이 NumberStyles.AllowLeadingWhite 표시될 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingWhite 경우 styles 끝에 표시될 수 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 매개 변수의 메서드 provider 에서 반환된 NumberFormatInfo 개체의 속성에 GetFormat 의해 NumberFormatInfo.CurrencyPositivePattern 정의됩니다. 플래그가 포함된 경우 style 통화 기호가 NumberStyles.AllowCurrencySymbols 나타날 수 있습니다.
sign 선택적 기호입니다. 플래그가 포함된 경우 의 s 시작 부분에 기호가 표시되거나 플래그가 NumberStyles.AllowLeadingSign 포함된 경우 styles 끝에 표시할 NumberStyles.AllowTrailingSignstyle 있습니다. 플래그가 포함된 NumberStyles.AllowParentheses 경우 style 괄호를 사용하여 s 음수 값을 나타낼 수 있습니다.
숫자

fractional_digits

exponential_digits
0에서 9까지의 숫자 시퀀스입니다. fractional_digits 경우 숫자 0만 유효합니다.
, 문화권별 천 단위 구분 기호입니다. 에 지정된 provider 문화권의 천 단위 구분 기호가 플래그를 포함하는 NumberStyles.AllowThousands 경우 styles 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 에 지정된 provider 문화권의 소수점 기호가 플래그를 포함하는 NumberStyles.AllowDecimalPoint 경우 styles 나타날 수 있습니다.

구문 분석 작업이 성공하려면 숫자 0만 소수 자릿수로 표시할 수 있습니다. fractional_digits 다른 숫자가 포함되어 있으면 이 OverflowException throw됩니다.
e 값이 지수 표기법으로 표시됨을 나타내는 'e' 또는 'E' 문자입니다. 플래그가 포함된 경우 style 매개 변수는 s 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
hexdigits 0에서 f까지 또는 0부터 F까지의 16진수 숫자 시퀀스입니다.

참고

의 종결 NUL(U+0000) 문자는 인수 값 style 에 관계없이 구문 분석 작업에서 s 무시됩니다.

10진수만 있는 문자열(스타일에 NumberStyles.None 해당)은 형식의 Int32 범위에 있는 경우 항상 성공적으로 구문 분석됩니다. 나머지 NumberStyles 멤버의 대부분은 이 입력 문자열에 있을 수 있지만 필요하지 않은 요소를 제어합니다. 다음 표에서는 개별 NumberStyles 멤버가 에 s있을 수 있는 요소에 미치는 영향을 나타냅니다.

복합이 아닌 NumberStyles 값 숫자 외에 에서 허용되는 요소
NumberStyles.None 10진수만.
NumberStyles.AllowDecimalPoint 소수점( . ) 및 소수 자릿수 요소입니다 . 그러나 소수 자릿수는 하나 이상의 0자리 숫자로만 구성되어야 합니다. 그렇지 않으면 이 OverflowException throw됩니다.
NumberStyles.AllowExponent 매개 변수는 s 지수 표기법을 사용할 수도 있습니다. 지수 표기법의 숫자를 나타내는 경우 s 0이 아닌 소수 구성 요소가 없는 데이터 형식 범위 내의 Int32 정수를 나타내야 합니다.
NumberStyles.AllowLeadingWhite 의 시작 부분에 있는 ws 요소입니다 s.
NumberStyles.AllowTrailingWhite 의 끝에 있는 ws 요소입니다 s.
NumberStyles.AllowLeadingSign 양수 기호가 숫자 앞에 나타날 수 있습니다.
NumberStyles.AllowTrailingSign 양수 기호는 숫자 다음에 나타날 수 있습니다.
NumberStyles.AllowParentheses 숫자 값을 묶는 괄호 형식의 기호 요소입니다.
NumberStyles.AllowThousands 천 단위 구분 기호( , ) 요소입니다.
NumberStyles.AllowCurrencySymbol $ 요소입니다.

플래그를 NumberStyles.AllowHexSpecifier 사용하는 s 경우 는 접두사 없이 16진수 값이어야 합니다. 예를 들어 "C9AF3"은 성공적으로 구문 분석되지만 "0xC9AF3"은 구문 분석하지 않습니다. 에 style 있을 수 있는 유일한 다른 플래그는 및 NumberStyles.AllowTrailingWhite입니다NumberStyles.AllowLeadingWhite. NumberStyles(열거형에는 공백 플래그를 모두 포함하는 복합 숫자 스타일 NumberStyles.HexNumber가 있습니다.)

매개 변수는 provider 또는 개체와 같은 구현입니다 NumberFormatInfoIFormatProviderCultureInfo. 매개 변수는 provider 구문 분석에 사용되는 문화권별 정보를 제공합니다. 가 이 nullNumberFormatInfoprovider 현재 문화권의 개체가 사용됩니다.

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 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)

Source:
Int32.cs
Source:
Int32.cs

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)

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

지정된 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 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비트 부호 있는 정수입니다.

구현

예외

s이(가) null인 경우

s의 형식이 올바르지 않습니다.

sInt32.MinValue 보다 작거나 Int32.MaxValue보다 큰 숫자를 나타냅니다.

예제

다음 예제는 웹 양식의 단추 클릭 이벤트 처리기입니다. 속성에서 반환된 배열을 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 . 소수 자릿수 외에도 선행 기호와 함께 선행 및 후행 공백만 허용됩니다. 에 s있을 수 있는 스타일 요소를 명시적으로 정의하려면 메서드를 Int32.Parse(String, NumberStyles, IFormatProvider) 사용합니다.

매개 변수는 provider 또는 개체와 같은 구현입니다 NumberFormatInfoIFormatProviderCultureInfo. 매개 변수는 provider 형식 s에 대한 문화권별 정보를 제공합니다. 가 이 nullNumberFormatInfoprovider 현재 문화권의 개체가 사용됩니다.

추가 정보

적용 대상

Parse(String)

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

숫자의 문자열 표현을 해당하는 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비트 부호 있는 정수입니다.

예외

s이(가) null인 경우

s가 올바른 형식이 아닙니다.

sInt32.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]

대괄호([ 및 ])의 항목은 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 Description
ws 선택적 공백입니다.
sign 선택적 기호입니다.
숫자 0에서 9 사이의 숫자 시퀀스입니다.

매개 변수는 s 스타일을 사용하여 해석됩니다 NumberStyles.Integer . 소수 자릿수 외에도 선행 기호와 함께 선행 및 후행 공백만 허용됩니다. 에 s있을 수 있는 스타일 요소를 명시적으로 정의하려면 또는 메서드를 Int32.Parse(String, NumberStyles)Int32.Parse(String, NumberStyles, IFormatProvider) 사용합니다.

s 매개 변수는 현재 시스템 문화권에 대해 초기화된 개체의 NumberFormatInfo 서식 정보를 사용하여 구문 분석됩니다. 자세한 내용은 CurrentInfo를 참조하세요. 다른 문화권의 서식 정보를 사용하여 문자열을 구문 분석하려면 메서드를 Int32.Parse(String, NumberStyles, IFormatProvider) 사용합니다.

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

문자 범위를 값으로 구문 분석합니다.

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)

Source:
Int32.cs
Source:
Int32.cs

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)

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

지정된 스타일로 된 숫자의 문자열 표현을 해당하는 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비트 부호 있는 정수입니다.

예외

s이(가) null인 경우

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifierHexNumber 값의 조합이 아닙니다.

sstyle 규격 형식이 아닙니다.

sInt32.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] [$] [기호] [digits,]digits[.fractional_digits][e[sign]exponential_digits][ws]

또는 가 포함된 경우 style 입니다 AllowHexSpecifier.

[ws]hexdigits[ws]

대괄호([ 및 ])의 항목은 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 설명
ws 선택적 공백입니다. 플래그를 포함하는 경우 style 의 시작 부분에 s 공백이 NumberStyles.AllowLeadingWhite 표시될 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingWhite 경우 styles 끝에 표시될 수 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 현재 문화권의 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 속성에 의해 정의됩니다. 플래그가 포함된 경우 style 현재 문화권의 통화 기호가 NumberStyles.AllowCurrencySymbols 나타날 수 있습니다.
sign 선택적 기호입니다. 플래그가 포함된 경우 style 의 시작 부분에 s 기호가 NumberStyles.AllowLeadingSign 표시되고 플래그가 포함된 NumberStyles.AllowTrailingSign 경우 styles 끝에 표시할 수 있습니다. 플래그가 포함된 NumberStyles.AllowParentheses 경우 style 괄호를 사용하여 s 음수 값을 나타낼 수 있습니다.
숫자

fractional_digits

exponential_digits
0에서 9까지의 숫자 시퀀스입니다. fractional_digits 경우 숫자 0만 유효합니다.
, 문화권별 천 단위 구분 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 천 단위 구분 기호가 NumberStyles.AllowThousandss 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 소수점 기호가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다. 구문 분석 작업이 성공하려면 숫자 0만 소수 자릿수로 표시할 수 있습니다. fractional_digits 다른 숫자가 포함되어 있으면 이 OverflowException throw됩니다.
e 값이 지수 표기법으로 표시됨을 나타내는 'e' 또는 'E' 문자입니다. 플래그가 포함된 경우 style 매개 변수는 s 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
hexdigits 0에서 f까지 또는 0부터 F까지의 16진수 숫자 시퀀스입니다.

참고

의 종결 NUL(U+0000) 문자는 인수 값 style 에 관계없이 구문 분석 작업에서 s 무시됩니다.

숫자만 있는 문자열(스타일에 NumberStyles.None 해당)은 형식의 Int32 범위에 있는 경우 항상 성공적으로 구문 분석됩니다. 나머지 NumberStyles 멤버의 대부분은 입력 문자열에 존재할 필요는 없지만 존재할 필요는 없는 요소를 제어합니다. 다음 표에서는 개별 NumberStyles 멤버가 에 s있을 수 있는 요소에 미치는 영향을 나타냅니다.

NumberStyles 값 숫자 외에 에서 허용되는 요소
None digits 요소만 해당합니다.
AllowDecimalPoint 소수점( . ) 및 소수 자릿수 요소입니다 .
AllowExponent 매개 변수는 s 지수 표기법을 사용할 수도 있습니다.
AllowLeadingWhite 의 시작 부분에 있는 ws 요소입니다 s.
AllowTrailingWhite 의 끝에 있는 ws 요소입니다 s.
AllowLeadingSign 의 시작 부분에 있는 기호 요소입니다 s.
AllowTrailingSign 의 끝에 있는 기호 요소입니다 s.
AllowParentheses 숫자 값을 묶는 괄호 형식의 기호 요소입니다.
AllowThousands 천 단위 구분 기호( , ) 요소입니다.
AllowCurrencySymbol $ 요소입니다.
Currency 모두. 매개 변수는 s 16진수 또는 지수 표기법으로 숫자를 나타낼 수 없습니다.
Float s시작 또는 끝에 있는 ws 요소, 의 s시작 부분에 기호, 소수점( . ) 기호입니다. 매개 변수는 s 지수 표기법을 사용할 수도 있습니다.
Number ws, , sign천 단위 구분 기호( , ) 및 소수점( . ) 요소입니다.
Any 를 제외한 s 모든 스타일은 16진수를 나타낼 수 없습니다.

플래그를 NumberStyles.AllowHexSpecifier 사용하는 s 경우 는 접두사 없이 16진수 값이어야 합니다. 예를 들어 "C9AF3"은 성공적으로 구문 분석되지만 "0xC9AF3"은 구문 분석하지 않습니다. 매개 변수와 s 결합할 수 있는 유일한 다른 플래그는 및 NumberStyles.AllowTrailingWhite입니다NumberStyles.AllowLeadingWhite. (열거형에는 NumberStyles 공백 플래그를 모두 포함하는 복합 숫자 스타일 NumberStyles.HexNumber가 포함됩니다.)

s 매개 변수는 현재 시스템 문화권에 대해 초기화된 개체의 NumberFormatInfo 서식 정보를 사용하여 구문 분석됩니다. 구문 분석 작업에 서식 정보가 사용되는 문화권을 지정하려면 오버로드를 호출합니다 Int32.Parse(String, NumberStyles, IFormatProvider) .

추가 정보

적용 대상