Single.Parse 메서드

정의

숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

오버로드

Parse(String, NumberStyles, IFormatProvider)

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을포함하는 문자 범위를 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

UTF-8자의 범위를 값으로 구문 분석합니다.

Parse(String, IFormatProvider)

지정된 문화권별 형식의 숫자에 대한 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

Parse(String)

숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Parse(ReadOnlySpan<Byte>, IFormatProvider)

UTF-8자의 범위를 값으로 구문 분석합니다.

Parse(String, NumberStyles)

지정된 스타일로 된 숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

Parse(String, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

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

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다.

style
NumberStyles

s에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 AllowThousands와 결합되는 Float입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

반환

s에 지정된 숫자 값 또는 기호에 해당하는 단정밀도 부동 소수점 숫자입니다.

구현

예외

s이(가) null인 경우

s가 숫자 값을 나타내지 않는 경우

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifier 값입니다.

.NET Framework 및 .NET Core 2.2 이하 버전만: sSingle.MinValue보다 작거나 Single.MaxValue보다 큰 숫자를 나타냅니다.

예제

다음 코드 예제에서는 메서드를 Parse(String, NumberStyles, IFormatProvider) 사용하여 값의 Single 문자열 표현을 구문 분석합니다. 배열의 각 문자열은 en-US, nl-NL 및 사용자 지정 문화권의 서식 지정 규칙을 사용하여 구문 분석됩니다. 사용자 지정 문화권은 해당 그룹 구분 기호를 밑줄("_")로 정의하고 그룹 크기를 2로 정의합니다.

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
      // Define an array of string values.
      string[] values = { " 987.654E-2", " 987,654E-2",  "(98765,43210)",
                          "9,876,543.210", "9.876.543,210",  "98_76_54_32,19" };
      // Create a custom culture based on the invariant culture.
      CultureInfo ci = new CultureInfo("");
      ci.NumberFormat.NumberGroupSizes = new int[] { 2 };
      ci.NumberFormat.NumberGroupSeparator = "_";

      // Define an array of format providers.
      CultureInfo[] providers = { new CultureInfo("en-US"),
                                  new CultureInfo("nl-NL"), ci };

      // Define an array of styles.
      NumberStyles[] styles = { NumberStyles.Currency, NumberStyles.Float };

      // Iterate the array of format providers.
      foreach (CultureInfo provider in providers)
      {
         Console.WriteLine("Parsing using the {0} culture:",
                           provider.Name == String.Empty ? "Invariant" : provider.Name);
         // Parse each element in the array of string values.
         foreach (string value in values)
         {
            foreach (NumberStyles style in styles)
            {
               try {
                  float number = Single.Parse(value, style, provider);
                  Console.WriteLine("   {0} ({1}) -> {2}",
                                    value, style, number);
               }
               catch (FormatException) {
                  Console.WriteLine("   '{0}' is invalid using {1}.", value, style);
               }
               catch (OverflowException) {
                  Console.WriteLine("   '{0}' is out of the range of a Single.", value);
               }
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
// Parsing using the en-US culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the nl-NL culture:
//    ' 987.654E-2' is invalid using Currency.
//    ' 987.654E-2' is invalid using Float.
//    ' 987,654E-2' is invalid using Currency.
//     987,654E-2 (Float) -> 9.87654
//    (98765,43210) (Currency) -> -98765.43
//    '(98765,43210)' is invalid using Float.
//    '9,876,543.210' is invalid using Currency.
//    '9,876,543.210' is invalid using Float.
//    9.876.543,210 (Currency) -> 9876543
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the Invariant culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    98_76_54_32,19 (Currency) -> 9.876543E+09
//    '98_76_54_32,19' is invalid using Float.
open System
open System.Globalization

// Define a list of string values.
let values = 
    [ " 987.654E-2"; " 987,654E-2"; "(98765,43210)"
      "9,876,543.210"; "9.876.543,210"; "98_76_54_32,19" ]
// Create a custom culture based on the invariant culture.
let ci = CultureInfo ""
ci.NumberFormat.NumberGroupSizes <- [| 2 |]
ci.NumberFormat.NumberGroupSeparator <- "_"

// Define a list of format providers.
let providers = 
    [ CultureInfo "en-US"
      CultureInfo "nl-NL"
      ci ]

// Define a list of styles.
let styles = [ NumberStyles.Currency; NumberStyles.Float ]

// Iterate the list of format providers.
for provider in providers do
    printfn $"""Parsing using the {if provider.Name = String.Empty then "Invariant" else provider.Name} culture:"""
    // Parse each element in the array of string values.
    for value in values do
        for style in styles do
            try
                let number = Single.Parse(value, style, provider)
                printfn $"   {value} ({style}) -> {number}"
            with
            | :? FormatException ->
                printfn $"   '{value}' is invalid using {style}."
            | :? OverflowException ->
                printfn $"   '{value}' is out of the range of a Single."
    printfn ""

// The example displays the following output:
// Parsing using the en-US culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the nl-NL culture:
//    ' 987.654E-2' is invalid using Currency.
//    ' 987.654E-2' is invalid using Float.
//    ' 987,654E-2' is invalid using Currency.
//     987,654E-2 (Float) -> 9.87654
//    (98765,43210) (Currency) -> -98765.43
//    '(98765,43210)' is invalid using Float.
//    '9,876,543.210' is invalid using Currency.
//    '9,876,543.210' is invalid using Float.
//    9.876.543,210 (Currency) -> 9876543
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the Invariant culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    98_76_54_32,19 (Currency) -> 9.876543E+09
//    '98_76_54_32,19' is invalid using Float.
Imports System.Globalization

Module Example
    Public Sub Main()
      ' Define an array of string values.
      Dim values() As String = { " 987.654E-2", " 987,654E-2", _
                                 "(98765,43210)", "9,876,543.210",  _
                                 "9.876.543,210",  "98_76_54_32,19" }
      ' Create a custom culture based on the invariant culture.
      Dim ci As New CultureInfo("")
      ci.NumberFormat.NumberGroupSizes = New Integer() { 2 }
      ci.NumberFormat.NumberGroupSeparator = "_"
      
      ' Define an array of format providers.
      Dim providers() As CultureInfo = { New CultureInfo("en-US"), _
                                             New CultureInfo("nl-NL"), ci }       
      
      ' Define an array of styles.
      Dim styles() As NumberStyles = { NumberStyles.Currency, NumberStyles.Float }
      
      ' Iterate the array of format providers.
      For Each provider As CultureInfo In providers
         Console.WriteLine("Parsing using the {0} culture:", _
                           If(provider.Name = String.Empty, "Invariant", provider.Name))
         ' Parse each element in the array of string values.
         For Each value As String In values
            For Each style As NumberStyles In styles
               Try
                  Dim number As Single = Single.Parse(value, style, provider)            
                  Console.WriteLine("   {0} ({1}) -> {2}", _
                                    value, style, number)
               Catch e As FormatException
                  Console.WriteLine("   '{0}' is invalid using {1}.", value, style)            
               Catch e As OverflowException
                  Console.WriteLine("   '{0}' is out of the range of a Single.", value)
               End Try 
            Next            
         Next         
         Console.WriteLine()
      Next
   End Sub   
End Module 
' The example displays the following output:
'       Parsing using the en-US culture:
'          ' 987.654E-2' is invalid using Currency.
'           987.654E-2 (Float) -> 9.87654
'          ' 987,654E-2' is invalid using Currency.
'          ' 987,654E-2' is invalid using Float.
'          (98765,43210) (Currency) -> -9.876543E+09
'          '(98765,43210)' is invalid using Float.
'          9,876,543.210 (Currency) -> 9876543
'          '9,876,543.210' is invalid using Float.
'          '9.876.543,210' is invalid using Currency.
'          '9.876.543,210' is invalid using Float.
'          '98_76_54_32,19' is invalid using Currency.
'          '98_76_54_32,19' is invalid using Float.
'       
'       Parsing using the nl-NL culture:
'          ' 987.654E-2' is invalid using Currency.
'          ' 987.654E-2' is invalid using Float.
'          ' 987,654E-2' is invalid using Currency.
'           987,654E-2 (Float) -> 9.87654
'          (98765,43210) (Currency) -> -98765.43
'          '(98765,43210)' is invalid using Float.
'          '9,876,543.210' is invalid using Currency.
'          '9,876,543.210' is invalid using Float.
'          9.876.543,210 (Currency) -> 9876543
'          '9.876.543,210' is invalid using Float.
'          '98_76_54_32,19' is invalid using Currency.
'          '98_76_54_32,19' is invalid using Float.
'       
'       Parsing using the Invariant culture:
'          ' 987.654E-2' is invalid using Currency.
'           987.654E-2 (Float) -> 9.87654
'          ' 987,654E-2' is invalid using Currency.
'          ' 987,654E-2' is invalid using Float.
'          (98765,43210) (Currency) -> -9.876543E+09
'          '(98765,43210)' is invalid using Float.
'          9,876,543.210 (Currency) -> 9876543
'          '9,876,543.210' is invalid using Float.
'          '9.876.543,210' is invalid using Currency.
'          '9.876.543,210' is invalid using Float.
'          98_76_54_32,19 (Currency) -> 9.876543E+09
'          '98_76_54_32,19' is invalid using Float.

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

매개 변수는 style 구문 분석 작업이 성공하기 위해 매개 변수에 s 허용되는 스타일 요소(예: 공백, 천 단위 구분 기호 및 통화 기호)를 정의합니다. 열거형의 비트 플래그 NumberStyles 조합이어야 합니다. 다음 NumberStyles 멤버는 지원되지 않습니다.

매개 변수는 s 에서 지정한 provider문화권에 대해 , NumberFormatInfo.NegativeInfinitySymbol또는 NumberFormatInfo.NaNSymbol 를 포함NumberFormatInfo.PositiveInfinitySymbol할 수 있습니다. 의 값 style에 따라 다음과 같은 형식을 사용할 수도 있습니다.

[ws] [$] [sign][정수 자릿수,]정수 자릿수[.[ fractional-digits]] [E[sign]exponential-digits] [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 음수 값을 나타낼 수 있습니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 문자열 에 fractional-digits 요소가 포함된 경우 정 수 자릿수 요소가 없을 수 있습니다.
, 문화권별 그룹 구분 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 그룹 구분 기호가 NumberStyles.AllowThousandss 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 소수점 기호가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 플래그가 포함된 경우 style 소수 자릿수가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.
E 값이 지수(과학적) 표기법으로 표시됨을 나타내는 "e" 또는 "E" 문자입니다. 플래그가 포함된 경우 style 매개 변수는 s 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
exponential-digits 지수를 지정하는 0에서 9까지의 일련의 숫자입니다.

참고

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

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

NumberStyles 값 숫자 외에 에서 s 허용되는 요소
None 정수 자릿수 요소만 해당합니다.
AllowDecimalPoint 소수점(.) 및 소수 자릿수 요소입니다 .
AllowExponent 지수 표기법을 나타내는 "e" 또는 "E" 문자입니다. 이 플래그는 그 자체로 양식 숫자 E 숫자의 값을 지원합니다. 양수 또는 음수 기호 및 소수점 기호와 같은 요소를 사용하여 문자열을 성공적으로 구문 분석하려면 추가 플래그가 필요합니다.
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진수를 나타낼 수 없습니다.

매개 변수는 provider 구현입니다 IFormatProvider . 해당 메서드는 GetFormat 형식valueNumberFormatInfo 대한 문화권별 정보를 제공하는 개체를 반환합니다. 일반적으로 는 provider 다음 중 하나일 수 있습니다.

  • CultureInfo 숫자 서식 정보를 제공하는 문화권을 나타내는 개체입니다. 해당 메서드는 GetFormatNumberFormatInfo 숫자 서식 정보를 제공하는 개체를 반환합니다.

  • NumberFormatInfo 서식 정보를 제공하는 개체입니다. (의 구현은 GetFormat 그 자체를 반환합니다.)

  • 메서드를 IFormatProvider 구현하고 사용하여 GetFormat 서식 정보를 제공하는 개체를 인스턴스화하고 반환 NumberFormatInfo 하는 사용자 지정 개체입니다.

가 이 nullNumberFormatInfoprovider 현재 문화권의 개체가 사용됩니다.

가 데이터 형식 범위를 Single 벗어나면 s 메서드는 .NET Framework 및 .NET Core 2.2 이전 버전에서 을 throw OverflowException 합니다. .NET Core 3.0 이상 버전에서는 가 보다 작으면 s 를 반환하고 Single.PositiveInfinity 가 보다 Single.MaxValueSingle.MinValue 크면 s 를 반환 Single.NegativeInfinity 합니다.

구문 분석 작업 중에 매개 변수에서 s 구분 기호가 발견되고 해당 통화 또는 숫자 10진수 및 그룹 구분 기호가 동일한 경우 구문 분석 작업은 구분 기호가 그룹 구분 기호가 아닌 소수 구분 기호라고 가정합니다. 구분 기호에 대한 자세한 내용은 , , NumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator를 참조CurrencyDecimalSeparator하세요.

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

지정된 스타일 및 문화권별 형식으로 된 숫자의 문자열 표현을포함하는 문자 범위를 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

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

매개 변수

s
ReadOnlySpan<Char>

변환될 숫자가 포함된 문자 범위입니다.

style
NumberStyles

s에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 AllowThousands와 결합되는 Float입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

반환

s에 지정된 숫자 값 또는 기호에 해당하는 단정밀도 부동 소수점 숫자입니다.

구현

예외

s가 숫자 값을 나타내지 않는 경우

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifier 값입니다.

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

가 데이터 형식 범위를 벗어나면 s 가 보다 작으면 s 를 반환하고 Single.PositiveInfinity 가 보다 Single.MaxValueSingle.MinValue 크면 s 을 반환 Single.NegativeInfinity 합니다.Single

적용 대상

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs

UTF-8자의 범위를 값으로 구문 분석합니다.

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

구문 분석할 UTF-8자의 범위입니다.

style
NumberStyles

utf8Text있을 수 있는 숫자 스타일의 비트 조합입니다.

provider
IFormatProvider

utf8Text에 대한 문화권별 서식 정보를 제공하는 개체입니다.

반환

구문 분석의 결과입니다 utf8Text.

구현

적용 대상

Parse(String, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

지정된 문화권별 형식의 숫자에 대한 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

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

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다.

provider
IFormatProvider

s에 대한 문화권별 형식 지정 정보를 제공하는 개체입니다.

반환

s에 지정된 숫자 값 또는 기호에 해당하는 단정밀도 부동 소수점 숫자입니다.

구현

예외

s이(가) null인 경우

s가 유효한 형식의 숫자를 나타내지 않습니다.

.NET Framework 및 .NET Core 2.2 이하 버전만: sSingle.MinValue보다 작거나 Single.MaxValue보다 큰 숫자를 나타냅니다.

예제

다음 예제는 웹 양식의 단추 클릭 이벤트 처리기입니다. 속성에서 반환된 배열을 HttpRequest.UserLanguages 사용하여 사용자의 로캘을 확인합니다. 그런 다음 해당 로캘에 CultureInfo 해당하는 개체를 인스턴스화합니다. NumberFormatInfo 그런 다음 해당 CultureInfo 개체에 속하는 개체가 메서드에 Parse(String, IFormatProvider) 전달되어 사용자의 입력을 값으로 Single 변환합니다.

protected void OkToSingle_Click(object sender, EventArgs e)
{
    string locale;
    float 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 = Single.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 OkToSingle_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToSingle.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Single

   ' 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 = Single.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As OverflowException
      Exit Sub
   End Try

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

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

이 오버로드는 일반적으로 다양한 방법으로 서식을 지정할 수 있는 텍스트를 값으로 Single 변환하는 데 사용됩니다. 예를 들어 사용자가 입력한 텍스트를 HTML 텍스트 상자로 숫자 값으로 변환하는 데 사용할 수 있습니다.

매개 변수는 sNumberStyles.AllowThousands 플래그의 조합을 사용하여 해석됩니다NumberStyles.Float. 매개 변수는 s 에 지정된 provider문화권에 대해 , NumberFormatInfo.NegativeInfinitySymbol또는 NumberFormatInfo.NaNSymbol 을 포함NumberFormatInfo.PositiveInfinitySymbol하거나 형식의 문자열을 포함할 수 있습니다.

[ws] [기호] 정수 자릿수[.[fractional-digits]] [E[sign]exponential-digits] [ws]

선택적 요소는 대괄호([ 및 ])로 프레임화됩니다. "digits"라는 용어가 포함된 요소는 0에서 9 사이의 일련의 숫자 문자로 구성됩니다.

요소 설명
ws 일련의 공백 문자입니다.
sign 음수 기호(-) 또는 양수 기호 기호(+)입니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 정수 자릿수의 실행은 그룹 구분 기호로 분할할 수 있습니다. 예를 들어 일부 문화권에서는 쉼표(,)가 수천 개의 그룹을 구분합니다. 문자열 에 fractional-digits 요소가 포함된 경우 정 수 자릿수 요소가 없을 수 있습니다.
. 문화권별 소수점 기호입니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다.
E 값이 지수(과학적) 표기법으로 표시됨을 나타내는 "e" 또는 "E" 문자입니다.
exponential-digits 지수를 지정하는 0에서 9까지의 일련의 숫자입니다.

숫자 형식에 대한 자세한 내용은 형식 지정 항목을 참조하세요.

provider 매개 변수는 메서드가 IFormatProviderGetFormat 문화권별 서식 지정 정보를 제공하는 개체를 NumberFormatInfo 반환하는 구현입니다. 메서드가 Parse(String, IFormatProvider) 호출되면 매개 변수의 GetFormat 메서드를 provider 호출하고 형식을 나타내는 개체로 Type 전달합니다NumberFormatInfo. 그런 다음 메서드는 GetFormat 매개 변수의 형식에 대한 정보를 제공하는 개체를 반환 NumberFormatInfo 합니다 s . 매개 변수를 사용하여 provider 구문 분석 작업에 사용자 지정 서식 정보를 제공하는 세 가지 방법이 있습니다.

  • 서식 정보를 제공하는 문화권을 나타내는 개체를 전달할 CultureInfo 수 있습니다. 해당 메서드는 GetFormat 해당 문화권에 NumberFormatInfo 대한 숫자 서식 정보를 제공하는 개체를 반환합니다.

  • 숫자 서식 정보를 제공하는 실제 NumberFormatInfo 개체를 전달할 수 있습니다. (의 구현은 GetFormat 그 자체를 반환합니다.)

  • 를 구현하는 사용자 지정 개체를 전달할 수 있습니다 IFormatProvider. 해당 메서드는 GetFormat 서식 정보를 제공하는 개체를 NumberFormatInfo 인스턴스화하고 반환합니다.

null 또는 를 NumberFormatInfo 가져올 수 없는 경우 provider 현재 시스템 문화권에 대한 서식 지정 정보가 사용됩니다.

가 데이터 형식 범위를 Single 벗어나면 s 메서드는 .NET Framework 및 .NET Core 2.2 이전 버전에서 을 throw OverflowException 합니다. .NET Core 3.0 이상 버전에서는 가 보다 작으면 s 를 반환하고 Single.PositiveInfinity 가 보다 Single.MaxValueSingle.MinValue 크면 s 를 반환 Single.NegativeInfinity 합니다.

구문 분석 작업 중에 매개 변수에서 s 구분 기호가 발견되고 해당 통화 또는 숫자 10진수 및 그룹 구분 기호가 동일한 경우 구문 분석 작업은 구분 기호가 그룹 구분 기호가 아닌 소수 구분 기호라고 가정합니다. 구분 기호에 대한 자세한 내용은 , , NumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator를 참조CurrencyDecimalSeparator하세요.

s 의 예로는 "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123" 및 "-Infinity"가 있습니다.

추가 정보

적용 대상

Parse(String)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

public:
 static float Parse(System::String ^ s);
public static float Parse (string s);
static member Parse : string -> single
Public Shared Function Parse (s As String) As Single

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다.

반환

s에 지정된 숫자 값 또는 기호에 해당하는 단정밀도 부동 소수점 숫자입니다.

예외

s이(가) null인 경우

s가 유효한 형식의 숫자를 나타내지 않습니다.

.NET Framework 및 .NET Core 2.2 이하 버전만: sSingle.MinValue보다 작거나 Single.MaxValue보다 큰 숫자를 나타냅니다.

예제

다음 예제에서는 메서드를 Parse(String) 사용하여 문자열 배열을 동등한 Single 값으로 변환합니다.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "100", "(100)", "-123,456,789", "123.45e+6", 
                          "+500", "5e2", "3.1416", "600.", "-.123", 
                          "-Infinity", "-1E-16", Double.MaxValue.ToString(), 
                          Single.MinValue.ToString(), String.Empty };
      foreach (string value in values)
      {
         try {   
            float number = Single.Parse(value);
            Console.WriteLine("{0} -> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("'{0}' is not in a valid format.", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0} is outside the range of a Single.", value);
         }
      }                                  
   }
}
// The example displays the following output:
//       100 -> 100
//       '(100)' is not in a valid format.
//       -123,456,789 -> -1.234568E+08
//       123.45e+6 -> 1.2345E+08
//       +500 -> 500
//       5e2 -> 500
//       3.1416 -> 3.1416
//       600. -> 600
//       -.123 -> -0.123
//       -Infinity -> -Infinity
//       -1E-16 -> -1E-16
//       1.79769313486232E+308 is outside the range of a Single.
//       -3.402823E+38 -> -3.402823E+38
//       '' is not in a valid format.
open System

let values = 
    [| "100"; "(100)"; "-123,456,789"; "123.45e+6" 
       "+500"; "5e2"; "3.1416"; "600."; "-.123" 
       "-Infinity"; "-1E-16"; string Double.MaxValue
       string Single.MinValue; String.Empty |]

for value in values do
    try
        let number = Single.Parse value
        printfn $"{value} -> {number}"
    with
    | :? FormatException ->
        printfn $"'{value}' is not in a valid format."
    | :? OverflowException ->
        printfn $"{value} is outside the range of a Single."
// The example displays the following output:
//       100 -> 100
//       '(100)' is not in a valid format.
//       -123,456,789 -> -1.234568E+08
//       123.45e+6 -> 1.2345E+08
//       +500 -> 500
//       5e2 -> 500
//       3.1416 -> 3.1416
//       600. -> 600
//       -.123 -> -0.123
//       -Infinity -> -Infinity
//       -1E-16 -> -1E-16
//       1.79769313486232E+308 is outside the range of a Single.
//       -3.402823E+38 -> -3.402823E+38
//       '' is not in a valid format.
Module Example
   Public Sub Main()
      Dim values() As String = { "100", "(100)", "-123,456,789", "123.45e+6", _
                                 "+500", "5e2", "3.1416", "600.", "-.123", _
                                 "-Infinity", "-1E-16", Double.MaxValue.ToString(), _
                                 Single.MinValue.ToString(), String.Empty }
      For Each value As String In values
         Try   
            Dim number As Single = Single.Parse(value)
            Console.WriteLine("{0} -> {1}", value, number)
         Catch e As FormatException
            Console.WriteLine("'{0}' is not in a valid format.", value)
         Catch e As OverflowException
            Console.WriteLine("{0} is outside the range of a Single.", value)
         End Try
      Next                                  
   End Sub
End Module
' The example displays the following output:
'       100 -> 100
'       '(100)' is not in a valid format.
'       -123,456,789 -> -1.234568E+08
'       123.45e+6 -> 1.2345E+08
'       +500 -> 500
'       5e2 -> 500
'       3.1416 -> 3.1416
'       600. -> 600
'       -.123 -> -0.123
'       -Infinity -> -Infinity
'       -1E-16 -> -1E-16
'       1.79769313486232E+308 is outside the range of a Single.
'       -3.402823E+38 -> -3.402823E+38
'       '' is not in a valid format.

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

매개 변수는 s 현재 문화권의 PositiveInfinitySymbol, , NegativeInfinitySymbolNaNSymbol또는 폼의 문자열을 포함할 수 있습니다.

[ws] [기호] [정수 자릿수[,]] 정수 자릿수[.[fractional-digits]] [e[sign]exponential-digits] [ws]

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

요소 설명
ws 일련의 공백 문자입니다.
sign 음수 기호 또는 양수 기호입니다. 유효한 부호 문자는 현재 문화권의 NumberFormatInfo.NegativeSignNumberFormatInfo.PositiveSign 속성에 의해 결정됩니다. 선행 기호만 사용할 수 있습니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 정수 자릿수의 실행은 그룹 구분 기호로 분할할 수 있습니다. 예를 들어 일부 문화권에서는 쉼표(,)가 수천 개의 그룹을 구분합니다. 문자열 에 fractional-digits 요소가 포함된 경우 정 수 자릿수 요소가 없을 수 있습니다.
, 문화권별 천 단위 구분 기호입니다.
. 문화권별 소수점 기호입니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다.
E 값이 지수(과학적) 표기법으로 표시됨을 나타내는 "e" 또는 "E" 문자입니다.
exponential-digits 지수를 지정하는 0에서 9까지의 일련의 숫자입니다.

매개 변수는 sNumberStyles.AllowThousands 플래그의 조합을 사용하여 해석됩니다NumberStyles.Float. 즉, 공백과 수천 개의 구분 기호가 허용되지만 통화 기호는 허용되지 않습니다. 에 있을 s수 있는 요소(예: 통화 기호, 천 단위 구분 기호 및 공백)를 명시적으로 정의하려면 메서드 오버로드를 Parse(String, NumberStyles) 사용합니다.

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

일반적으로 메서드를 Parse 호출 ToString 하여 만든 문자열을 메서드에 전달하면 원래 Single 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다.

가 데이터 형식 범위를 Single 벗어나면 s 메서드는 .NET Framework 및 .NET Core 2.2 이전 버전에서 을 throw OverflowException 합니다. .NET Core 3.0 이상 버전에서는 가 보다 작으면 s 를 반환하고 Single.PositiveInfinity 가 보다 Single.MaxValueSingle.MinValue 크면 s 를 반환 Single.NegativeInfinity 합니다.

구문 분석 작업 중에 매개 변수에서 s 구분 기호가 발견되고 해당 통화 또는 숫자 10진수 및 그룹 구분 기호가 동일한 경우 구문 분석 작업은 구분 기호가 그룹 구분 기호가 아닌 소수 구분 기호라고 가정합니다. 구분 기호에 대한 자세한 내용은 , , NumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator를 참조CurrencyDecimalSeparator하세요.

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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

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

매개 변수

s
ReadOnlySpan<Char>

구문 분석할 문자의 범위입니다.

provider
IFormatProvider

s에 대한 문화권별 서식 정보를 제공하는 개체입니다.

반환

구문 분석의 결과입니다 s.

구현

적용 대상

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
Single.cs
Source:
Single.cs

UTF-8자의 범위를 값으로 구문 분석합니다.

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

구문 분석할 UTF-8자의 범위입니다.

provider
IFormatProvider

utf8Text에 대한 문화권별 서식 정보를 제공하는 개체입니다.

반환

구문 분석의 결과입니다 utf8Text.

구현

적용 대상

Parse(String, NumberStyles)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

지정된 스타일로 된 숫자의 문자열 표현을 해당하는 단정밀도 부동 소수점 숫자로 변환합니다.

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

매개 변수

s
String

변환할 숫자가 포함된 문자열입니다.

style
NumberStyles

s에 나타날 수 있는 스타일 요소를 나타내는 열거형 값의 비트 조합입니다. 지정할 일반적인 값은 AllowThousands와 결합되는 Float입니다.

반환

s에 지정된 숫자 값 또는 기호에 해당하는 단정밀도 부동 소수점 숫자입니다.

예외

s이(가) null인 경우

s는 유효한 형식의 숫자가 아닙니다.

.NET Framework 및 .NET Core 2.2 이하 버전만: sSingle.MinValue보다 작거나 Single.MaxValue보다 큰 숫자를 나타냅니다.

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifier 값이 포함되어 있습니다.

예제

다음 예제에서는 메서드를 Parse(String, NumberStyles) 사용하여 값의 Single 문자열 표현을 구문 분석합니다. 이 예제에서는 en-US 문화권에 대한 서식 정보를 사용합니다.

using System;
using System.Globalization;
using System.Threading;

public class ParseString
{
   public static void Main()
   {
      // Set current thread culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      
      string value;
      NumberStyles styles;
      
      // Parse a string in exponential notation with only the AllowExponent flag. 
      value = "-1.063E-02";
      styles = NumberStyles.AllowExponent;
      ShowNumericValue(value, styles);
      
      // Parse a string in exponential notation
      // with the AllowExponent and Number flags.
      styles = NumberStyles.AllowExponent | NumberStyles.Number;
      ShowNumericValue(value, styles);

      // Parse a currency value with leading and trailing white space, and
      // white space after the U.S. currency symbol.
      value = " $ 6,164.3299  ";
      styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
      ShowNumericValue(value, styles);
      
      // Parse negative value with thousands separator and decimal.
      value = "(4,320.64)";
      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float; 
      ShowNumericValue(value, styles);
      
      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float | NumberStyles.AllowThousands;
      ShowNumericValue(value, styles);
   }

   private static void ShowNumericValue(string value, NumberStyles styles)
   {
      Single number;
      try
      {
         number = Single.Parse(value, styles);
         Console.WriteLine("Converted '{0}' using {1} to {2}.", 
                           value, styles.ToString(), number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to parse '{0}' with styles {1}.", 
                           value, styles.ToString());
      }
      Console.WriteLine();                           
   }   
}
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//    
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//    
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//    
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//    
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
open System
open System.Globalization
open System.Threading

let showNumericValue value (styles: NumberStyles) =
    try
        let number = Single.Parse(value, styles)
        printfn $"Converted '{value}' using {styles} to {number}."
    with :? FormatException ->
        printfn $"Unable to parse '{value}' with styles {styles}."
    printfn ""

[<EntryPoint>]
let main _ =
    // Set current thread culture to en-US.
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"
    
    // Parse a string in exponential notation with only the AllowExponent flag. 
    let value = "-1.063E-02"
    let styles = NumberStyles.AllowExponent
    showNumericValue value styles
    
    // Parse a string in exponential notation
    // with the AllowExponent and Number flags.
    let styles = NumberStyles.AllowExponent ||| NumberStyles.Number
    showNumericValue value styles

    // Parse a currency value with leading and trailing white space, and
    // white space after the U.S. currency symbol.
    let value = " $ 6,164.3299  "
    let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
    showNumericValue value styles
    
    // Parse negative value with thousands separator and decimal.
    let value = "(4,320.64)"
    let styles = NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float 
    showNumericValue value styles
    
    let styles = NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
    showNumericValue value styles
    0
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//    
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//    
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//    
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//    
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Imports System.Globalization
Imports System.Threading

Module ParseStrings
   Public Sub Main()
      ' Set current thread culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
            
      Dim value As String
      Dim styles As NumberStyles
      
      ' Parse a string in exponential notation with only the AllowExponent flag. 
      value = "-1.063E-02"
      styles = NumberStyles.AllowExponent
      ShowNumericValue(value, styles) 
      
      ' Parse a string in exponential notation
      ' with the AllowExponent and Number flags.
      styles = NumberStyles.AllowExponent Or NumberStyles.Number
      ShowNumericValue(value, styles)

      ' Parse a currency value with leading and trailing white space, and
      ' white space after the U.S. currency symbol.
      value = " $ 6,164.3299  "
      styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
      ShowNumericValue(value, styles)
      
      ' Parse negative value with thousands separator and decimal.
      value = "(4,320.64)"
      styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
               Or NumberStyles.Float 
      ShowNumericValue(value, styles)
      
      styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
               Or NumberStyles.Float Or NumberStyles.AllowThousands
      ShowNumericValue(value, styles)
   End Sub
   
   Private Sub ShowNumericValue(value As String, styles As NumberStyles)
      Dim number As Single
      Try
         number = Single.Parse(value, styles)
         Console.WriteLine("Converted '{0}' using {1} to {2}.", _
                           value, styles.ToString(), number)
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
                           value, styles.ToString())
      End Try
      Console.WriteLine()                           
   End Sub
End Module
' The example displays the following output to the console:
'    Unable to parse '-1.063E-02' with styles AllowExponent.
'    
'    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'    
'    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
'    
'    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'    
'    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.

설명

.NET Core 3.0 이상에서는 너무 커서 나타낼 수 없는 값이 IEEE 754 사양에 따라 반올림 PositiveInfinity 되거나 NegativeInfinity 필요합니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

매개 변수는 style 구문 분석 작업이 성공하기 위해 매개 변수에 s 허용되는 스타일 요소(예: 공백, 천 단위 구분 기호 및 통화 기호)를 정의합니다. 열거형의 비트 플래그 NumberStyles 조합이어야 합니다. 다음 NumberStyles 멤버는 지원되지 않습니다.

매개 변수는 s 현재 문화권의 PositiveInfinitySymbol, , 를 NegativeInfinitySymbolNaNSymbol포함할 수 있습니다. 의 값 style에 따라 다음과 같은 형식을 사용할 수도 있습니다.

[ws] [$][sign][정수 자릿수[,]]정수 자릿수[.[fractional-digits]] [E[sign]exponential-digits] [ws]

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

Ws 일련의 공백 문자입니다. 플래그를 포함하는 경우 style 의 시작 부분에 s 공백이 NumberStyles.AllowLeadingWhite 표시될 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingWhite 경우 styles 끝에 표시될 수 있습니다.

$ 문화권별 통화 기호입니다. 문자열의 위치는 현재 문화권의 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 속성에 의해 정의됩니다. 플래그가 포함된 경우 style 현재 문화권의 통화 기호가 NumberStyles.AllowCurrencySymbols 나타날 수 있습니다.

서명 음수 기호(-) 또는 양수 기호 기호(+)입니다. 플래그가 포함된 경우 style 의 시작 부분에 s 기호가 NumberStyles.AllowLeadingSign 표시되고 플래그가 포함된 NumberStyles.AllowTrailingSign 경우 styles 끝에 표시할 수 있습니다. 플래그가 포함된 NumberStyles.AllowParentheses 경우 style 괄호를 사용하여 s 음수 값을 나타낼 수 있습니다.

정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 문자열 에 fractional-digits 요소가 포함된 경우 정 수 자릿수 요소가 없을 수 있습니다.

문화권별 그룹 구분 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 그룹 구분 기호가 NumberStyles.AllowThousandss 나타날 수 있습니다.

. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 소수점 기호가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.

fractional-digits 숫자의 소수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 플래그가 포함된 경우 style 소수 자릿수가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.

E 값이 지수(과학적) 표기법으로 표시됨을 나타내는 "e" 또는 "E" 문자입니다. 플래그가 포함된 경우 style 매개 변수는 value 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.

exponential-digits 지수를 지정하는 0에서 9까지의 일련의 숫자입니다.

참고

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

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

NumberStyles 값 숫자 외에 에서 s 허용되는 요소
None 정수 자릿수 요소만 해당합니다.
AllowDecimalPoint 소수점(.) 및 소수 자릿수 요소입니다 .
AllowExponent 지수 표기법을 나타내는 "e" 또는 "E" 문자입니다. 이 플래그는 그 자체로 양식 숫자 E 숫자의 값을 지원합니다. 양수 또는 음수 기호 및 소수점 기호와 같은 요소를 사용하여 문자열을 성공적으로 구문 분석하려면 추가 플래그가 필요합니다.
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진수를 나타낼 수 없습니다.

s 의 예로는 "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123" 및 "-Infinity"가 있습니다.

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

일반적으로 메서드를 Parse 호출 ToString 하여 만든 문자열을 메서드에 전달하면 원래 Single 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다.

가 데이터 형식 범위를 Single 벗어나면 s 메서드는 .NET Framework 및 .NET Core 2.2 이전 버전에서 을 throw OverflowException 합니다. .NET Core 3.0 이상 버전에서는 가 보다 작으면 s 를 반환하고 Single.PositiveInfinity 가 보다 Single.MaxValueSingle.MinValue 크면 s 를 반환 Single.NegativeInfinity 합니다.

구문 분석 작업 중에 매개 변수에서 s 구분 기호가 발견되고 해당 통화 또는 숫자 10진수 및 그룹 구분 기호가 동일한 경우 구문 분석 작업은 구분 기호가 그룹 구분 기호가 아닌 소수 구분 기호라고 가정합니다. 구분 기호에 대한 자세한 내용은 , , NumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator를 참조CurrencyDecimalSeparator하세요.

추가 정보

적용 대상