Int32.Parse 메서드
정의
숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.Converts the string representation of a number to its 32-bit signed integer equivalent.
오버로드
Parse(String, NumberStyles, IFormatProvider) |
지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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) |
지정된 스타일로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.Converts the string representation of a number in a specified style to its 32-bit signed integer equivalent. |
Parse(String) |
숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.Converts the string representation of a number to its 32-bit signed integer equivalent. |
Parse(String, IFormatProvider) |
지정된 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.Converts the string representation of a number in a specified culture-specific format to its 32-bit signed integer equivalent. |
Parse(String, NumberStyles, IFormatProvider)
지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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 (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
변환할 숫자가 포함된 문자열입니다.A string containing a number to convert.
- style
- NumberStyles
s
에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. 지정할 일반적인 값은 Integer입니다.A typical value to specify is Integer.
- provider
- IFormatProvider
s
의 형식에 대한 문화권별 정보를 제공하는 개체입니다.An object that supplies culture-specific information about the format of s
.
반환
s
에 지정된 수에 해당하는 32비트 부호 있는 정수입니다.A 32-bit signed integer equivalent to the number specified in s
.
예외
s
이(가) null
인 경우s
is null
.
style
이 NumberStyles 값이 아닙니다.style
is not a NumberStyles value.
또는-or-
style
이 AllowHexSpecifier 및 HexNumber 값의 조합이 아닙니다.style
is not a combination of AllowHexSpecifier and HexNumber values.
s
가 style
규격 형식이 아닙니다.s
is not in a format compliant with style
.
s
는 MinValue보다 작거나 MaxValue보다 큰 숫자를 나타냅니다.s
represents a number less than MinValue or greater than MaxValue.
또는-or-
s
에 0이 아닌 소수 자릿수가 포함되어 있습니다.s
includes non-zero, fractional digits.
예제
다음 예제에서는 다양 style
한 및 매개 변수를 사용 하 여 provider
값의 문자열 표현을 구문 분석 합니다 Int32 .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.
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
구문 분석 작업이 성공 하기 위해 매개 변수에 허용 되는 스타일 요소 (예: 공백 또는 양수 기호)를 정의 합니다.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. 열거형의 비트 플래그 조합 이어야 합니다 NumberStyles .It must be a combination of bit flags from the NumberStyles enumeration. 의 값에 따라 style
s
매개 변수는 다음 요소를 포함할 수 있습니다.Depending on the value of style
, the s
parameter may include the following elements:
ws-trust [$] 로그인 [숫자,] 숫자 [.fractional_digist] [e [sign] exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digist][e[sign]exponential_digits][ws]
또는 다음이 style
포함 되는 경우 AllowHexSpecifier :Or, if style
includes AllowHexSpecifier:
[ws] hexdigits [ws][ws]hexdigits[ws]
대괄호 ([및]) 안의 항목은 선택 사항입니다.Items in square brackets ([ and ]) are optional. 다음 표에서는 각 요소에 대해 설명합니다.The following table describes each element.
요소Element | 설명Description |
---|---|
wsws | 선택적 공백입니다.Optional white space. 에 플래그가 포함 된 경우의 시작 부분에 공백이 표시 될 수 있으며 s style NumberStyles.AllowLeadingWhite ,에 플래그가 포함 된 경우 끝에 표시 될 수 있습니다 s style NumberStyles.AllowTrailingWhite .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. 문자열에서의 해당 위치는 NumberFormatInfo.CurrencyPositivePattern NumberFormatInfo GetFormat 매개 변수의 메서드에서 반환 하는 개체의 속성에 의해 정의 됩니다 provider .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. 에 플래그가 포함 된 경우에 통화 기호가 나타날 수 있습니다 s style NumberStyles.AllowCurrencySymbol .The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | 선택적 기호입니다.An optional sign. 기호에 플래그가 포함 된 s 경우 style NumberStyles.AllowLeadingSign 또는의 끝에 s style 플래그가 포함 된 경우 부호는의 시작 부분에 나타날 수 있습니다 NumberStyles.AllowTrailingSign .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. 에서 괄호를 사용 하 여에 s style 플래그가 포함 된 경우 음수 값을 나타낼 수 있습니다 NumberStyles.AllowParentheses .Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
숫자digits fractional_digitsfractional_digits exponential_digitsexponential_digits |
0부터 9 까지의 숫자 시퀀스입니다.A sequence of digits from 0 through 9. Fractional_digits 의 경우 숫자 0만 유효 합니다.For fractional_digits, only the digit 0 is valid. |
,, | 문화권별 천 단위 구분 기호입니다.A culture-specific thousands separator symbol. 로 지정 된 문화권의 천 단위 구분 기호는 provider 에 s 플래그가 포함 된 경우에 나타날 수 있습니다 style NumberStyles.AllowThousands .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. 로 지정 된 문화권의 소수점 기호는 provider 에 플래그가 포함 된 경우에 나타날 수 있습니다 s style NumberStyles.AllowDecimalPoint .The decimal point symbol of the culture specified by provider can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.구문 분석 작업이 성공 하려면 숫자 0만 소수 자릿수로 표시 될 수 있습니다. fractional_digits 에 다른 숫자가 포함 되어 있으면 OverflowException 이 throw 됩니다.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. |
ee | ' E ' 또는 ' E ' 문자는 값이 지 수 표기법으로 표시 됨을 나타냅니다.The 'e' or 'E' character, which indicates that the value is represented in exponential notation. s 매개 변수는 style 플래그가 포함 된 경우 지 수 표기법으로 숫자를 나타낼 수 있습니다 NumberStyles.AllowExponent .The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. |
hexdigitshexdigits | 0부터 f 까지의 16 진수 또는 0에서 F 까지의 16 진수 시퀀스입니다.A sequence of hexadecimal digits from 0 through f, or 0 through F. |
참고
의 모든 종료 NUL (U + 0000) 문자는 s
인수 값에 관계 없이 구문 분석 작업에서 무시 됩니다 style
.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
10 진수 숫자만 포함 하는 문자열 (스타일에 해당 NumberStyles.None )은 형식 범위에 있을 경우 항상 성공적으로 구문 분석 Int32 합니다.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. 나머지 멤버는 대부분 NumberStyles 이 입력 문자열에 포함 될 수 있는 요소를 제어 합니다.Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. 다음 표에서는 개별 NumberStyles 멤버가에 있을 수 있는 요소에 영향을 주는 방법을 보여 줍니다 s
.The following table indicates how individual NumberStyles members affect the elements that may be present in s
.
비 복합 NumberStyles 값Non-composite NumberStyles values | 숫자 외에 s에서 허용 되는 요소Elements permitted in s in addition to digits |
---|---|
NumberStyles.None | 10 진수입니다.Decimal digits only. |
NumberStyles.AllowDecimalPoint | 소수점 ( .The decimal point ( . ) 및 소수 자릿수 요소가 있습니다.) and fractional-digits elements. 그러나 소수 자릿수 는 하나 이상의 0 자리로 구성 되어야 합니다 OverflowException . 그렇지 않으면이 throw 됩니다.However, fractional-digits must consist of only one or more 0 digits or an OverflowException is thrown. |
NumberStyles.AllowExponent | s 매개 변수는 지 수 표기법을 사용할 수도 있습니다.The s parameter can also use exponential notation. 가 s 지 수 표기법으로 숫자를 나타내는 경우에는 Int32 0이 아닌 소수 부분을 포함 하지 않는 데이터 형식의 범위 내에 있는 정수를 나타내야 합니다.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 | 의 시작 부분에 있는 ws 요소 s 입니다.The ws element at the beginning of s . |
NumberStyles.AllowTrailingWhite | 의 끝에 있는 ws 요소 s 입니다.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. |
플래그를 NumberStyles.AllowHexSpecifier 사용 하는 경우는 s
접두사가 없는 16 진수 값 이어야 합니다.If the NumberStyles.AllowHexSpecifier flag is used, s
must be a hexadecimal value without a prefix. 예를 들어 "C9AF3"는 성공적으로 구문 분석 되지만 "0xC9AF3"은 그렇지 않습니다.For example, "C9AF3" parses successfully, but "0xC9AF3" does not. 에 있을 수 있는 다른 플래그는 및 뿐 style
입니다 NumberStyles.AllowLeadingWhite NumberStyles.AllowTrailingWhite .The only other flags that can be present in style
are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. 열거형에는 공백 NumberStyles NumberStyles.HexNumber 플래그를 모두 포함 하는 복합 숫자 스타일이 있습니다.(The NumberStyles enumeration has a composite number style, NumberStyles.HexNumber, that includes both white space flags.)
provider
매개 변수는 IFormatProvider 또는 개체와 같은 구현입니다 NumberFormatInfo CultureInfo .The provider
parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. provider
매개 변수는 구문 분석에 사용 되는 문화권별 정보를 제공 합니다.The provider
parameter supplies culture-specific information used in parsing. provider
가 이면 null
NumberFormatInfo 현재 문화권에 대 한 개체가 사용 됩니다.If provider
is null
, the NumberFormatInfo object for the current culture is used.
추가 정보
적용 대상
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
지정된 스타일 및 문화권별 형식으로 된 숫자의 범위 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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
매개 변수
- s
- ReadOnlySpan<Char>
변환할 숫자를 나타내는 문자를 포함하는 범위입니다.A span containing the characters representing the number to convert.
- style
- NumberStyles
s
에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다.A bitwise combination of enumeration values that indicates the style elements that can be present in s
. 지정할 일반적인 값은 Integer입니다.A typical value to specify is Integer.
- provider
- IFormatProvider
s
의 형식에 대한 문화권별 정보를 제공하는 개체입니다.An object that supplies culture-specific information about the format of s
.
반환
s
에 지정된 수에 해당하는 32비트 부호 있는 정수입니다.A 32-bit signed integer equivalent to the number specified in s
.
적용 대상
Parse(String, NumberStyles)
지정된 스타일로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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
매개 변수
- s
- String
변환할 숫자가 포함된 문자열입니다.A string containing a number to convert.
- style
- NumberStyles
s
에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다.A bitwise combination of the enumeration values that indicates the style elements that can be present in s
. 지정할 일반적인 값은 Integer입니다.A typical value to specify is Integer.
반환
s
에 지정된 수에 해당하는 32비트 부호 있는 정수입니다.A 32-bit signed integer equivalent to the number specified in s
.
예외
s
이(가) null
인 경우s
is null
.
style
이 NumberStyles 값이 아닙니다.style
is not a NumberStyles value.
또는-or-
style
이 AllowHexSpecifier 및 HexNumber 값의 조합이 아닙니다.style
is not a combination of AllowHexSpecifier and HexNumber values.
s
가 style
규격 형식이 아닙니다.s
is not in a format compliant with style
.
s
는 MinValue보다 작거나 MaxValue보다 큰 숫자를 나타냅니다.s
represents a number less than MinValue or greater than MaxValue.
또는-or-
s
에 0이 아닌 소수 자릿수가 포함되어 있습니다.s
includes non-zero, fractional digits.
예제
다음 예제에서는 메서드를 사용 하 여 Int32.Parse(String, NumberStyles) 여러 값의 문자열 표현을 구문 분석 합니다 Int32 .The following example uses the Int32.Parse(String, NumberStyles) method to parse the string representations of several Int32 values. 예제의 현재 문화권이 en-us입니다.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.
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
구문 분석 작업이 성공 하기 위해 매개 변수에 허용 되는 스타일 요소 (예: 공백, 양수 또는 음수 기호 또는 천 단위 구분 기호)를 정의 합니다.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. 열거형의 비트 플래그 조합 이어야 합니다 NumberStyles .It must be a combination of bit flags from the NumberStyles enumeration. 의 값에 따라 style
s
매개 변수는 다음 요소를 포함할 수 있습니다.Depending on the value of style
, the s
parameter may include the following elements:
ws-trust [$] 로그인 [숫자,] 숫자 [.fractional_digits] [e [sign] exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digits][e[sign]exponential_digits][ws]
또는 다음이 style
포함 되는 경우 AllowHexSpecifier :Or, if style
includes AllowHexSpecifier:
[ws] hexdigits [ws][ws]hexdigits[ws]
대괄호 ([및]) 안의 항목은 선택 사항입니다.Items in square brackets ([ and ]) are optional. 다음 표에서는 각 요소에 대해 설명합니다.The following table describes each element.
요소Element | 설명Description |
---|---|
wsws | 선택적 공백입니다.Optional white space. 에 플래그가 포함 된 경우의 시작 부분에 공백이 표시 될 수 있으며 s style NumberStyles.AllowLeadingWhite ,에 플래그가 포함 된 경우 끝에 표시 될 수 있습니다 s style NumberStyles.AllowTrailingWhite .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. 문자열에서의 해당 위치는 NumberFormatInfo.CurrencyNegativePattern 현재 문화권의 및 속성에 의해 정의 됩니다 NumberFormatInfo.CurrencyPositivePattern .Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 에 플래그가 포함 된 경우 현재 문화권의 통화 기호가에 표시 될 수 있습니다 s style NumberStyles.AllowCurrencySymbol .The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag. |
signsign | 선택적 기호입니다.An optional sign. 에 플래그가 포함 된 경우 부호는의 시작 부분에 나타날 수 있으며 s style ,에 NumberStyles.AllowLeadingSign s 플래그가 포함 된 경우 끝에 표시 될 style NumberStyles.AllowTrailingSign 수 있습니다.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. 에서 괄호를 사용 하 여에 s style 플래그가 포함 된 경우 음수 값을 나타낼 수 있습니다 NumberStyles.AllowParentheses .Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag. |
숫자digits fractional_digitsfractional_digits exponential_digitsexponential_digits |
0부터 9 까지의 숫자 시퀀스입니다.A sequence of digits from 0 through 9. Fractional_digits 의 경우 숫자 0만 유효 합니다.For fractional_digits, only the digit 0 is valid. |
,, | 문화권별 천 단위 구분 기호입니다.A culture-specific thousands separator symbol. 에 플래그가 포함 된 경우 현재 문화권의 천 단위 구분 기호가에 표시 될 수 있습니다 s style NumberStyles.AllowThousands .The current culture's thousands separator can appear in s if style includes the NumberStyles.AllowThousands flag. |
.. | 문화권별 소수점 기호입니다.A culture-specific decimal point symbol. 에 플래그가 포함 된 경우 현재 문화권의 소수점 기호가에 표시 될 수 있습니다 s style NumberStyles.AllowDecimalPoint .The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag. 구문 분석 작업이 성공 하려면 숫자 0만 소수 자릿수로 표시 될 수 있습니다. fractional_digits 에 다른 숫자가 포함 되어 있으면 OverflowException 이 throw 됩니다.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. |
ee | ' E ' 또는 ' E ' 문자는 값이 지 수 표기법으로 표시 됨을 나타냅니다.The 'e' or 'E' character, which indicates that the value is represented in exponential notation. s 매개 변수는 style 플래그가 포함 된 경우 지 수 표기법으로 숫자를 나타낼 수 있습니다 NumberStyles.AllowExponent .The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag. |
hexdigitshexdigits | 0부터 f 까지의 16 진수 또는 0에서 F 까지의 16 진수 시퀀스입니다.A sequence of hexadecimal digits from 0 through f, or 0 through F. |
참고
의 모든 종료 NUL (U + 0000) 문자는 s
인수 값에 관계 없이 구문 분석 작업에서 무시 됩니다 style
.Any terminating NUL (U+0000) characters in s
are ignored by the parsing operation, regardless of the value of the style
argument.
숫자만 포함 하는 문자열 (스타일에 해당 NumberStyles.None )은 형식이 형식의 범위에 있는 경우 항상 성공적으로 구문 분석 Int32 합니다.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. 나머지 멤버는 대부분 NumberStyles 입력 문자열에 있을 수 있지만 반드시 필요한 것은 아닙니다.Most of the remaining NumberStyles members control elements that may be but are not required to be present in the input string. 다음 표에서는 개별 NumberStyles 멤버가에 있을 수 있는 요소에 영향을 주는 방법을 보여 줍니다 s
.The following table indicates how individual NumberStyles members affect the elements that may be present in s
.
NumberStyles 값NumberStyles value | 숫자 외에 s에서 허용 되는 요소Elements permitted in s in addition to digits |
---|---|
None | 숫자 요소만 있습니다.The digits element only. |
AllowDecimalPoint | 소수점 ( .The decimal point ( . ) 및 소수 자릿수 요소가 있습니다.) and fractional-digits elements. |
AllowExponent | s 매개 변수는 지 수 표기법을 사용할 수도 있습니다.The s parameter can also use exponential notation. |
AllowLeadingWhite | 의 시작 부분에 있는 ws 요소 s 입니다.The ws element at the beginning of s . |
AllowTrailingWhite | 의 끝에 있는 ws 요소 s 입니다.The ws element at the end of s . |
AllowLeadingSign | 의 시작 부분에 있는 부호 요소 s 입니다.The sign element at the beginning of s . |
AllowTrailingSign | 의 끝에 있는 부호 요소 s 입니다.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. s 매개 변수는 지 수 표기법에서 16 진수 또는 숫자를 나타낼 수 없습니다.The s parameter cannot represent a hexadecimal number or a number in exponential notation. |
Float | 의 시작 부분이 나 끝 부분에 있는 ws 요소 s ,의 시작 부분에서 부호 , s 소수점 ( .The ws element at the beginning or end of s , sign at the beginning of s , and the decimal point ( . 화살표.) symbol. s 매개 변수는 지 수 표기법을 사용할 수도 있습니다.The s parameter can also use exponential notation. |
Number | ws , sign , 천 단위 구분 기호 ( , ) 및 소수점 ( .The ws , sign , thousands separator ( , ), and decimal point ( . elements.) elements. |
Any | 를 제외한 모든 스타일 s 은 16 진수를 나타낼 수 없습니다.All styles, except s cannot represent a hexadecimal number. |
플래그를 NumberStyles.AllowHexSpecifier 사용 하는 경우는 s
접두사가 없는 16 진수 값 이어야 합니다.If the NumberStyles.AllowHexSpecifier flag is used, s
must be a hexadecimal value without a prefix. 예를 들어 "C9AF3"는 성공적으로 구문 분석 되지만 "0xC9AF3"은 그렇지 않습니다.For example, "C9AF3" parses successfully, but "0xC9AF3" does not. 매개 변수와 함께 사용할 수 있는 유일한 플래그는 s
NumberStyles.AllowLeadingWhite 및 NumberStyles.AllowTrailingWhite 입니다.The only other flags that can be combined with the s
parameter it are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. 열거형에는 공백 NumberStyles NumberStyles.HexNumber 플래그를 모두 포함 하는 복합 숫자 스타일이 포함 되어 있습니다.(The NumberStyles enumeration includes a composite number style, NumberStyles.HexNumber, that includes both white space flags.)
s
매개 변수는 NumberFormatInfo 현재 시스템 문화권에 대해 초기화 되는 개체의 형식 지정 정보를 사용 하 여 구문 분석 됩니다.The s
parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 구문 분석 작업에 사용 되는 형식 지정 정보를 포함 하는 문화권을 지정 하려면 Int32.Parse(String, NumberStyles, IFormatProvider) 오버 로드를 호출 합니다.To specify the culture whose formatting information is used for the parse operation, call the Int32.Parse(String, NumberStyles, IFormatProvider) overload.
추가 정보
적용 대상
Parse(String)
숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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
매개 변수
- s
- String
변환할 숫자가 포함된 문자열입니다.A string containing a number to convert.
반환
s
에 있는 수에 해당하는 32비트 부호 있는 정수입니다.A 32-bit signed integer equivalent to the number contained in s
.
예외
s
이(가) null
인 경우s
is null
.
s
가 올바른 형식이 아닙니다.s
is not in the correct format.
s
는 MinValue보다 작거나 MaxValue보다 큰 숫자를 나타냅니다.s
represents a number less than MinValue or greater than MaxValue.
예제
다음 예제에서는 메서드를 사용 하 여 문자열 값을 32 비트 부호 있는 정수 값으로 변환 하는 방법을 보여 줍니다 Int32.Parse(String) .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
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
매개 변수에는 다음과 같은 형식이 포함 됩니다.The s
parameter contains a number of the form:
ws-trust [sign] 숫자 [ws][ws][sign]digits[ws]
대괄호 ([및]) 안의 항목은 선택 사항입니다.Items in square brackets ([ and ]) are optional. 다음 표에서는 각 요소에 대해 설명합니다.The following table describes each element.
요소Element | DescriptionDescription |
---|---|
wsws | 선택적 공백입니다.Optional white space. |
signsign | 선택적 기호입니다.An optional sign. |
숫자digits | 0에서 9 사이의 숫자 시퀀스입니다.A sequence of digits ranging from 0 to 9. |
s
매개 변수는 스타일을 사용 하 여 해석 됩니다 NumberStyles.Integer .The s
parameter is interpreted using the NumberStyles.Integer style. 10 진수 뿐만 아니라 선행 공백과 후행 공백만 선행 기호와 함께 사용할 수 있습니다.In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. 에 나타날 수 있는 스타일 요소를 명시적으로 정의 하려면 s
또는 메서드를 사용 Int32.Parse(String, NumberStyles) Int32.Parse(String, NumberStyles, IFormatProvider) 합니다.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.
s
매개 변수는 NumberFormatInfo 현재 시스템 문화권에 대해 초기화 된 개체의 형식 지정 정보를 사용 하 여 구문 분석 됩니다.The s
parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture. 자세한 내용은 CurrentInfo를 참조하세요.For more information, see CurrentInfo. 다른 문화권의 서식 지정 정보를 사용 하 여 문자열을 구문 분석 하려면 Int32.Parse(String, NumberStyles, IFormatProvider) 메서드를 사용 합니다.To parse a string using the formatting information of some other culture, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.
추가 정보
적용 대상
Parse(String, IFormatProvider)
지정된 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 32비트 부호 있는 정수로 변환합니다.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 (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
변환할 숫자가 포함된 문자열입니다.A string containing a number to convert.
- provider
- IFormatProvider
s
에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.An object that supplies culture-specific formatting information about s
.
반환
s
에 지정된 수에 해당하는 32비트 부호 있는 정수입니다.A 32-bit signed integer equivalent to the number specified in s
.
예외
s
이(가) null
인 경우s
is null
.
s
의 형식이 올바르지 않습니다.s
is not of the correct format.
s
는 MinValue보다 작거나 MaxValue보다 큰 숫자를 나타냅니다.s
represents a number less than MinValue or greater than MaxValue.
예제
다음 예제는 웹 폼의 단추 클릭 이벤트 처리기입니다.The following example is the button click event handler of a Web form. 속성에서 반환 된 배열을 사용 하 여 HttpRequest.UserLanguages 사용자의 로캘을 결정 합니다.It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. 그런 다음 해당 CultureInfo 로캘에 해당 하는 개체를 인스턴스화합니다.It then instantiates a CultureInfo object that corresponds to that locale. NumberFormatInfo그런 다음 해당 개체에 속하는 개체를 CultureInfo 메서드에 전달 하 여 Parse(String, IFormatProvider) 사용자의 입력을 값으로 변환 합니다 Int32 .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
설명
메서드의이 오버 로드 Parse(String, IFormatProvider) 는 일반적으로 다양 한 방법으로 서식이 지정 될 수 있는 텍스트를 값으로 변환 하는 데 사용 됩니다 Int32 .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. 예를 들어 사용자가 입력 한 텍스트를 HTML 텍스트 상자로 변환 하는 데 사용할 수 있습니다.For example, it can be used to convert the text entered by a user into an HTML text box to a numeric value.
s
매개 변수에는 다음과 같은 형식이 포함 됩니다.The s
parameter contains a number of the form:
ws-trust [sign] 숫자 [ws][ws][sign]digits[ws]
대괄호 ([및]) 안의 항목은 선택 사항입니다.Items in square brackets ([ and ]) are optional. 다음 표에서는 각 요소에 대해 설명합니다.The following table describes each element.
요소Element | 설명Description |
---|---|
wsws | 선택적 공백입니다.Optional white space. |
signsign | 선택적 기호입니다.An optional sign. |
숫자digits | 0에서 9 사이의 숫자 시퀀스입니다.A sequence of digits ranging from 0 to 9. |
s
매개 변수는 스타일을 사용 하 여 해석 됩니다 NumberStyles.Integer .The s
parameter is interpreted using the NumberStyles.Integer style. 10 진수 뿐만 아니라 선행 공백과 후행 공백만 선행 기호와 함께 사용할 수 있습니다.In addition to decimal digits, only leading and trailing spaces together with a leading sign are allowed. 에 나타날 수 있는 스타일 요소를 명시적으로 정의 하려면 s
메서드를 사용 Int32.Parse(String, NumberStyles, IFormatProvider) 합니다.To explicitly define the style elements that can be present in s
, use the Int32.Parse(String, NumberStyles, IFormatProvider) method.
provider
매개 변수는 IFormatProvider 또는 개체와 같은 구현입니다 NumberFormatInfo CultureInfo .The provider
parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. provider
매개 변수는의 형식에 대 한 문화권별 정보를 제공 합니다 s
.The provider
parameter supplies culture-specific information about the format of s
. provider
가 이면 null
NumberFormatInfo 현재 문화권에 대 한 개체가 사용 됩니다.If provider
is null
, the NumberFormatInfo object for the current culture is used.