다음을 통해 공유


Double.Parse 메서드

정의

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

오버로드

Name Description
Parse(String)

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

Parse(ReadOnlySpan<Byte>, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Parse(String, NumberStyles)

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

Parse(String, IFormatProvider)

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

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Parse(String, NumberStyles, IFormatProvider)

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

설명

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

Parse(String)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

s
String

변환할 숫자가 들어 있는 문자열입니다.

반환

에 지정된 s숫자 값 또는 기호와 동일한 배정밀도 부동 소수점 숫자입니다.

예외

snull입니다.

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

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

예제

다음 예제에서는 메서드의 사용을 보여 줍니다 Parse(String) .

public class Temperature {
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    public static Temperature Parse(string s) {
        Temperature temp = new Temperature();

        if( s.TrimEnd(null).EndsWith("'F") ) {
            temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
        }
        else if( s.TrimEnd(null).EndsWith("'C") ) {
            temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
        }
        else {
            temp.Value = Double.Parse(s);
        }

        return temp;
    }

    // The value holder
    protected double m_value;

    public double Value {
        get {
            return m_value;
        }
        set {
            m_value = value;
        }
    }

    public double Celsius {
        get {
            return (m_value-32.0)/1.8;
        }
        set {
            m_value = 1.8*value+32.0;
        }
    }
}
type Temperature() =
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    static member Parse(s: string) =
        let temp = Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        elif s.TrimEnd(null).EndsWith "'C" then
            temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        else
            temp.Value <- Double.Parse s
        temp

    member val Value = 0. with get, set

    member this.Celsius
        with get () =
            (this.Value - 32.) / 1.8
        and set (value) =
            this.Value <- 1.8 * value + 32.
Public Class Temperature
    ' Parses the temperature from a string in form
    ' [ws][sign]digits['F|'C][ws]
    Public Shared Function Parse(ByVal s As String) As Temperature
        Dim temp As New Temperature()

        If s.TrimEnd(Nothing).EndsWith("'F") Then
            temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
        Else
            If s.TrimEnd(Nothing).EndsWith("'C") Then
                temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
            Else
                temp.Value = Double.Parse(s)
            End If
        End If
        Return temp
    End Function 'Parse

    ' The value holder
    Protected m_value As Double

    Public Property Value() As Double
        Get
            Return m_value
        End Get
        Set(ByVal Value As Double)
            m_value = Value
        End Set
    End Property

    Public Property Celsius() As Double
        Get
            Return (m_value - 32) / 1.8
        End Get
        Set(ByVal Value As Double)
            m_value = Value * 1.8 + 32
        End Set
    End Property
End Class

설명

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

매개 변수는 s 현재 문화권 또는 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 기호를 포함할 수 있습니다. 이 문자열 비교는 .NET Core 3.0 이상 버전에서는 대/소문자를 구분하지 않지만 .NET Framework를 비롯한 이전 버전에서는 대/소문자를 구분합니다. 매개 변수는 s 폼의 문자열일 수도 있습니다.

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

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

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

매개 변수는 s 플래그와 NumberStyles.AllowThousands 플래그의 조합을 사용하여 해석됩니다NumberStyles.Float. 즉, 통화 기호는 허용되지 않지만 공백과 수천 개의 구분 기호가 허용됩니다. 구문 분석 작업이 성공하기 위해 허용되는 s 스타일 요소를 더 세부적으로 제어하려면 메서드를 호출 Double.Parse(String, NumberStyles) 합니다 Double.Parse(String, NumberStyles, IFormatProvider) .

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

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 문자열 표현 Double.MinValue 을 구문 분석하려고 시도하거나 Double.MaxValue 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 OverflowException. 다음 예제에서는 그림을 제공합니다.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework 및 .NET Core 2.2 및 이전 버전에서 데이터 형식 범위를 벗어난 경우 s 메서드는 을 throw합니다OverflowException.DoubleParse(String)

.NET Core 3.0 이상 버전에서는 데이터 형식 범위를 벗어난 경우 s 예외가 Double throw되지 않습니다. 대부분의 경우 메서드가 반환 Double.PositiveInfinity 되거나 Double.NegativeInfinity. 그러나 양수 또는 음수 무한대보다 최대값 또는 최소값에 더 가까운 것으로 간주되는 작은 값 Double 집합이 있습니다. 이러한 경우 메서드는 반환 Double.MaxValue 하거나 Double.MinValue.

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

추가 정보

적용 대상

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

provider
IFormatProvider

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

반환

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

구현

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

s
ReadOnlySpan<Char>

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

provider
IFormatProvider

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

반환

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

구현

적용 대상

Parse(String, NumberStyles)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

s
String

변환할 숫자가 들어 있는 문자열입니다.

style
NumberStyles

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

반환

에 지정된 s숫자 값 또는 기호와 동일한 배정밀도 부동 소수점 숫자입니다.

예외

snull입니다.

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

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

style가 값이 아닌 경우 NumberStyles

-또는-

style 에는 값이 AllowHexSpecifier 포함됩니다.

예제

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

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)
{
   double number;
   try
   {
      number = Double.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: string) (styles: NumberStyles) =
    try
        let number = Double.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.
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 Double
   Try
      number = Double.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
' 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 현재 문화권 또는 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 기호를 포함할 수 있습니다. 이 문자열 비교는 .NET Core 3.0 이상 버전에서는 대/소문자를 구분하지 않지만 .NET Framework를 비롯한 이전 버전에서는 대/소문자를 구분합니다. 값 style에 따라 매개 변수는 s 다음과 같은 형식을 사용할 수도 있습니다.

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

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

요소 묘사
ws 일련의 공백 문자입니다. 플래그가 포함된 경우 style 의 시작 부분에 s 공백이 NumberStyles.AllowLeadingWhite 표시될 수 있으며 플래그를 포함하는 NumberStyles.AllowTrailingWhite 경우 style 끝에 s 표시될 수 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 현재 문화권의 NumberFormatInfo.CurrencyNegativePattern 속성 및 NumberFormatInfo.CurrencyPositivePattern 속성에 의해 정의됩니다. 플래그가 포함된 경우 s 현재 문화권의 통화 기호가 styleNumberStyles.AllowCurrencySymbol 나타날 수 있습니다.
서명 음수 기호(-) 또는 양수 기호(+)입니다. 플래그가 포함된 경우 시작 부분에 s 표시할 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingSign 경우 style 끝에 s 표시할 수 있습니다.styleNumberStyles.AllowLeadingSign 플래그를 포함하는 s 경우 style 괄호를 사용하여 NumberStyles.AllowParentheses 음수 값을 나타낼 수 있습니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9 사이의 일련의 숫자입니다. 문자열 에 소수 자릿수 요소가 포함된 경우 정 수 계열 요소가 없을 수 있습니다.
, 문화권별 그룹 구분 기호입니다. 플래그가 포함된 NumberStyles.AllowThousands 경우 style 현재 문화권의 그룹 구분 기호가 s 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 s 현재 문화권의 소수점 기호가 styleNumberStyles.AllowDecimalPoint 나타날 수 있습니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9 사이의 일련의 숫자입니다. 플래그를 포함하는 경우 style 소수 자릿수가 sNumberStyles.AllowDecimalPoint 나타날 수 있습니다.
E 값이 지수(과학적) 표기법으로 표현됨을 나타내는 "e" 또는 "E" 문자입니다. 플래그를 포함하는 경우 s 매개 변수는 style 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
exponential-digits 지수를 지정하는 0에서 9 사이의 일련의 숫자입니다.

메모

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

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

NumberStyles 값 숫자 외에 s 허용되는 요소
None 정수 요소만 해당합니다.
AllowDecimalPoint 소수점(.) 및 소수 자릿수 요소입니다 .
AllowExponent 지수 표기법을 나타내는 "e" 또는 "E" 문자입니다. 이 플래그는 그 자체로 폼 숫자 E 숫자의 값을 지원합니다. 양수 또는 음수 기호 및 소수점 기호와 같은 요소로 문자열을 성공적으로 구문 분석하려면 추가 플래그가 필요합니다.
AllowLeadingWhite 의 시작 부분에 있는 ws 요소입니다 s.
AllowTrailingWhite 의 끝에 있는 ws 요소입니다 s.
AllowLeadingSign 의 시작 부분에 있는 sign 요소입니다 s.
AllowTrailingSign 의 끝에 있는 sign 요소입니다 s.
AllowParentheses 숫자 값을 묶는 괄호 형식의 기호 요소입니다.
AllowThousands 천 단위 구분 기호(,) 요소입니다.
AllowCurrencySymbol 통화($) 요소입니다.
Currency 모든 요소. 그러나 s 16진수 또는 지수 표기법의 숫자를 나타낼 수는 없습니다.
Float 시작 또는 끝에 s있는 ws 요소, 시작 s부분에 있는 기호 및 소수점(.) 기호입니다. 매개 변수는 s 지수 표기법을 사용할 수도 있습니다.
Number ws, sign천 단위 구분 기호(,) 및 소수점(.) 요소입니다.
Any 모든 요소. 그러나 s 16진수를 나타낼 수는 없습니다.

매개 s 변수는 현재 시스템 문화권에 대해 초기화된 개체의 NumberFormatInfo 서식 정보를 사용하여 구문 분석됩니다. 자세한 내용은 CurrentInfo를 참조하세요.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 문자열 표현 Double.MinValue 을 구문 분석하려고 시도하거나 Double.MaxValue 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 OverflowException. .NET Core 3.0 이상 버전에서는 구문 분석을 시도하거나 Double.PositiveInfinity 구문 MinValue 분석하려고 하면 반환 Double.NegativeInfinity 됩니다MaxValue. 다음 예제에서는 그림을 제공합니다.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework 및 .NET Core 2.2 및 이전 버전에서 데이터 형식 범위를 벗어난 경우 s 메서드는 을 throw합니다OverflowException.DoubleParse(String, NumberStyles)

.NET Core 3.0 이상 버전에서는 데이터 형식 범위를 벗어난 경우 s 예외가 Double throw되지 않습니다. 대부분의 경우 메서드가 Parse(String, NumberStyles) 반환 Double.PositiveInfinity 되거나 Double.NegativeInfinity. 그러나 양수 또는 음수 무한대보다 최대값 또는 최소값에 더 가까운 것으로 간주되는 작은 값 Double 집합이 있습니다. 이러한 경우 메서드는 반환 Double.MaxValue 하거나 Double.MinValue.

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

추가 정보

적용 대상

Parse(String, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

s
String

변환할 숫자가 들어 있는 문자열입니다.

provider
IFormatProvider

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

반환

에 지정된 s숫자 값 또는 기호와 동일한 배정밀도 부동 소수점 숫자입니다.

구현

예외

snull입니다.

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

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

예제

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

protected void OkToDouble_Click(object sender, EventArgs e)
{
    string locale;
    double 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 = Double.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (OverflowException)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDouble_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDouble.Click
    Dim locale As String
    Dim culture As CultureInfo
    Dim number As Double

    ' 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 = Double.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

설명

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

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

매개 변수는 s 플래그와 NumberStyles.AllowThousands 플래그의 조합을 사용하여 해석됩니다NumberStyles.Float. 매개 변수는 s 에 지정된 provider문화권의 기호 또는 NumberFormatInfo.NaNSymbol 기호를 포함NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbol할 수 있습니다. 이 문자열 비교는 .NET Core 3.0 이상 버전에서는 대/소문자를 구분하지 않지만 .NET Framework를 비롯한 이전 버전에서는 대/소문자를 구분합니다. 매개 변수에는 s 다음과 같은 형식의 문자열이 포함될 수도 있습니다.

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

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

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

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

provider 매개 변수는 메서드가 GetFormat 형식 해석 IFormatProvider 에 사용되는 문화권별 정보를 제공하는 개체를 반환 NumberFormatInfo 하는 구현입니다s. 일반적으로 개체 NumberFormatInfo 입니다 CultureInfo . 현재 null 시스템 문화권에 NumberFormatInfo 대한 서식 정보를 가져오거나 가져올 수 없는 경우 provider 사용됩니다.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 문자열 표현 Double.MinValue 을 구문 분석하려고 시도하거나 Double.MaxValue 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 OverflowException. .NET Core 3.0 이상 버전에서는 구문 분석을 시도하거나 Double.PositiveInfinity 구문 MinValue 분석하려고 하면 반환 Double.NegativeInfinity 됩니다MaxValue. 다음 예제에서는 그림을 제공합니다.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework 및 .NET Core 2.2 및 이전 버전에서 데이터 형식 범위를 벗어난 경우 s 메서드는 을 throw합니다OverflowException.DoubleParse(String, IFormatProvider)

.NET Core 3.0 이상 버전에서는 데이터 형식 범위를 벗어난 경우 s 예외가 Double throw되지 않습니다. 대부분의 경우 메서드가 Parse(String, IFormatProvider) 반환 Double.PositiveInfinity 되거나 Double.NegativeInfinity. 그러나 양수 또는 음수 무한대보다 최대값 또는 최소값에 더 가까운 것으로 간주되는 작은 값 Double 집합이 있습니다. 이러한 경우 메서드는 반환 Double.MaxValue 하거나 Double.MinValue.

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

추가 정보

적용 대상

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

public static double 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 -> double
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 Double

매개 변수

utf8Text
ReadOnlySpan<Byte>

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

style
NumberStyles

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

provider
IFormatProvider

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

반환

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

구현

적용 대상

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

public static double Parse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
public static double 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 -> double
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 Double

매개 변수

s
ReadOnlySpan<Char>

변환할 숫자가 들어 있는 문자 범위입니다.

style
NumberStyles

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

provider
IFormatProvider

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

반환

에 지정된 s숫자 값 또는 기호와 동일한 배정밀도 부동 소수점 숫자입니다.

구현

예외

s 은 숫자 값을 나타내지 않습니다.

style가 값이 아닌 경우 NumberStyles

-또는-

style 는 값입니다 AllowHexSpecifier .

설명

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

데이터 형식의 Double 범위를 벗어난 경우 s 메서드는 보다 작거나 Double.PositiveInfinity 보다 Double.MinValueDouble.MaxValue경우 s 를 반환 Double.NegativeInfinitys 합니다.

적용 대상

Parse(String, NumberStyles, IFormatProvider)

Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs
Source:
Double.cs

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

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

매개 변수

s
String

변환할 숫자가 들어 있는 문자열입니다.

style
NumberStyles

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

provider
IFormatProvider

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

반환

에 지정된 s숫자 값 또는 기호와 동일한 배정밀도 부동 소수점 숫자입니다.

구현

예외

snull입니다.

s 은 숫자 값을 나타내지 않습니다.

style가 값이 아닌 경우 NumberStyles

-또는-

style 는 값입니다 AllowHexSpecifier .

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

예제

다음 예제에서는 메서드를 사용하여 온도 값의 Parse(String, NumberStyles, IFormatProvider) 여러 문자열 표현을 개체에 할당하는 방법을 Temperature 보여 줍니다.

using System;
using System.Globalization;

public class Temperature
{
   // Parses the temperature from a string. Temperature scale is
   // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
   // of the string.
   public static Temperature Parse(string s, NumberStyles styles,
                                   IFormatProvider provider)
   {
      Temperature temp = new Temperature();

      if (s.TrimEnd(null).EndsWith("'F"))
      {
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                   styles, provider);
      }
      else
      {
         if (s.TrimEnd(null).EndsWith("'C"))
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                        styles, provider);
         else
            temp.Value = Double.Parse(s, styles, provider);
      }
      return temp;
   }

   // Declare private constructor so Temperature so only Parse method can
   // create a new instance
   private Temperature()   {}

   protected double m_value;

   public double Value
   {
      get { return m_value; }
      private set { m_value = value; }
   }

   public double Celsius
   {
      get { return (m_value - 32) / 1.8; }
      private set { m_value = value * 1.8 + 32; }
   }

   public double Fahrenheit
   {
      get {return m_value; }
   }
}

public class TestTemperature
{
   public static void Main()
   {
      string value;
      NumberStyles styles;
      IFormatProvider provider;
      Temperature temp;

      value = "25,3'C";
      styles = NumberStyles.Float;
      provider = CultureInfo.CreateSpecificCulture("fr-FR");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = " (40) 'C";
      styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
               | NumberStyles.AllowParentheses;
      provider = NumberFormatInfo.InvariantInfo;
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = "5,778E03'C";      // Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
               NumberStyles.AllowExponent;
      provider = CultureInfo.CreateSpecificCulture("en-GB");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"));
   }
}
open System
open System.Globalization

// Declare private constructor so Temperature so only Parse method can create a new instance
type Temperature private () =

    let mutable m_value = 0.

    member _.Value
        with get () = m_value
        and private set (value) = m_value <- value

    member _.Celsius
        with get() = (m_value - 32.) / 1.8
        and private set (value) = m_value <- value * 1.8 + 32.

    member _.Fahrenheit =
        m_value

    // Parses the temperature from a string. Temperature scale is
    // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
    // of the string.
    static member Parse(s: string, styles: NumberStyles, provider: IFormatProvider) =
        let temp = new Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
        else
            if s.TrimEnd(null).EndsWith "'C" then
                temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
            else
                temp.Value <- Double.Parse(s, styles, provider)
        temp

[<EntryPoint>]
let main _ =
    let value = "25,3'C"
    let styles = NumberStyles.Float
    let provider = CultureInfo.CreateSpecificCulture "fr-FR"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = " (40) 'C"
    let styles = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite ||| NumberStyles.AllowParentheses
    let provider = NumberFormatInfo.InvariantInfo
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = "5,778E03'C"      // Approximate surface temperature of the Sun
    let styles = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands ||| NumberStyles.AllowExponent
    let provider = CultureInfo.CreateSpecificCulture "en-GB"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit:N} degrees Fahrenheit equals {temp.Celsius:N} degrees Celsius."

    0
Imports System.Globalization

Public Class Temperature
   ' Parses the temperature from a string. Temperature scale is 
   ' indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
   ' of the string.
   Public Shared Function Parse(s As String, styles As NumberStyles, _
                                provider As IFormatProvider) As Temperature
      Dim temp As New Temperature()
      
      If s.TrimEnd(Nothing).EndsWith("'F") Then
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                   styles, provider)
      Else
         If s.TrimEnd(Nothing).EndsWith("'C") Then
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                        styles, provider)
         Else
            temp.Value = Double.Parse(s, styles, provider)         
         End If
      End If
      Return temp      
   End Function 
   
   ' Declare private constructor so Temperature so only Parse method can
   ' create a new instance
   Private Sub New 
   End Sub

   Protected m_value As Double
   
   Public Property Value() As Double
      Get
         Return m_value
      End Get
      
      Private Set
         m_value = Value
      End Set
   End Property
   
   Public Property Celsius() As Double
      Get
         Return (m_value - 32) / 1.8
      End Get
      Private Set
         m_value = Value * 1.8 + 32
      End Set
   End Property
   
   Public ReadOnly Property Fahrenheit() As Double
      Get
         Return m_Value
      End Get   
   End Property   
End Class

Public Module TestTemperature
   Public Sub Main
      Dim value As String
      Dim styles As NumberStyles
      Dim provider As IFormatProvider
      Dim temp As Temperature
      
      value = "25,3'C"
      styles = NumberStyles.Float
      provider = CultureInfo.CreateSpecificCulture("fr-FR")
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = " (40) 'C"
      styles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite _
               Or NumberStyles.AllowParentheses
      provider = NumberFormatInfo.InvariantInfo
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = "5,778E03'C"      ' Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
               NumberStyles.AllowExponent
      provider = CultureInfo.CreateSpecificCulture("en-GB") 
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"))
                                
   End Sub
End Module

설명

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

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

매개 변수는 s 에 지정된 provider문화권의 기호 또는 NumberFormatInfo.NaNSymbol 기호를 포함NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbol할 수 있습니다. 이 문자열 비교는 .NET Core 3.0 이상 버전에서는 대/소문자를 구분하지 않지만 .NET Framework를 비롯한 이전 버전에서는 대/소문자를 구분합니다. 값 style에 따라 매개 변수는 s 다음과 같은 형식을 사용할 수도 있습니다.

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

대괄호([ 및 ])로 프레임된 요소는 선택 사항입니다. 다음 표에서는 각 요소에 대해 설명합니다.

요소 묘사
ws 일련의 공백 문자입니다. 플래그가 포함된 경우 style 의 시작 부분에 s 공백이 NumberStyles.AllowLeadingWhite 표시될 수 있으며 플래그를 포함하는 NumberStyles.AllowTrailingWhite 경우 style 끝에 s 표시될 수 있습니다.
$ 문화권별 통화 기호입니다. 문자열의 위치는 현재 문화권의 NumberFormatInfo.CurrencyNegativePattern 속성 및 NumberFormatInfo.CurrencyPositivePattern 속성에 의해 정의됩니다. 플래그가 포함된 경우 s 현재 문화권의 통화 기호가 styleNumberStyles.AllowCurrencySymbol 나타날 수 있습니다.
서명 음수 기호(-) 또는 양수 기호(+)입니다. 플래그가 포함된 경우 시작 부분에 s 표시할 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingSign 경우 style 끝에 s 표시할 수 있습니다.styleNumberStyles.AllowLeadingSign 플래그를 포함하는 s 경우 style 괄호를 사용하여 NumberStyles.AllowParentheses 음수 값을 나타낼 수 있습니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9 사이의 일련의 숫자입니다. 문자열 에 소수 자릿수 요소가 포함된 경우 정 수 계열 요소가 없을 수 있습니다.
, 문화권별 그룹 구분 기호입니다. 플래그가 포함된 NumberStyles.AllowThousands 경우 style 현재 문화권의 그룹 구분 기호가 s 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 s 현재 문화권의 소수점 기호가 styleNumberStyles.AllowDecimalPoint 나타날 수 있습니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9 사이의 일련의 숫자입니다. 플래그를 포함하는 경우 style 소수 자릿수가 sNumberStyles.AllowDecimalPoint 나타날 수 있습니다.
E 값이 지수(과학적) 표기법으로 표현됨을 나타내는 "e" 또는 "E" 문자입니다. 플래그를 포함하는 경우 s 매개 변수는 style 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
exponential-digits 지수를 지정하는 0에서 9 사이의 일련의 숫자입니다.

메모

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

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

NumberStyles 값 숫자 외에 s 허용되는 요소
None 정수 요소만 해당합니다.
AllowDecimalPoint 소수점(.) 및 소수 자릿수 요소입니다 .
AllowExponent 지수 표기법을 나타내는 "e" 또는 "E" 문자입니다. 이 플래그는 그 자체로 폼 숫자 E 숫자의 값을 지원합니다. 양수 또는 음수 기호 및 소수점 기호와 같은 요소로 문자열을 성공적으로 구문 분석하려면 추가 플래그가 필요합니다.
AllowLeadingWhite 의 시작 부분에 있는 ws 요소입니다 s.
AllowTrailingWhite 의 끝에 있는 ws 요소입니다 s.
AllowLeadingSign 의 시작 부분에 있는 sign 요소입니다 s.
AllowTrailingSign 의 끝에 있는 sign 요소입니다 s.
AllowParentheses 숫자 값을 묶는 괄호 형식의 기호 요소입니다.
AllowThousands 천 단위 구분 기호(,) 요소입니다.
AllowCurrencySymbol 통화($) 요소입니다.
Currency 모든 요소. 그러나 s 16진수 또는 지수 표기법의 숫자를 나타낼 수는 없습니다.
Float 시작 또는 끝에 s있는 ws 요소, 시작 s부분에 있는 기호 및 소수점(.) 기호입니다. 매개 변수는 s 지수 표기법을 사용할 수도 있습니다.
Number ws, sign천 단위 구분 기호(,) 및 소수점(.) 요소입니다.
Any 모든 요소. 그러나 s 16진수를 나타낼 수는 없습니다.

provider 매개 변수는 메서드가 GetFormat 형식 해석 IFormatProvider 에 사용되는 문화권별 정보를 제공하는 개체를 반환 NumberFormatInfo 하는 구현입니다s. 일반적으로 개체 NumberFormatInfo 입니다 CultureInfo . 현재 null 시스템 문화권에 NumberFormatInfo 대한 서식 정보를 가져오거나 가져올 수 없는 경우 provider 사용됩니다.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 문자열 표현 MinValue 을 구문 분석하려고 시도하거나 Double.MaxValue 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 OverflowException. .NET Core 3.0 이상 버전에서는 구문 분석을 시도하거나 Double.PositiveInfinity 구문 MinValue 분석하려고 하면 반환 Double.NegativeInfinity 됩니다MaxValue. 다음 예제에서는 그림을 제공합니다.

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework 및 .NET Core 2.2 및 이전 버전에서 데이터 형식 범위를 벗어난 경우 s 메서드는 을 throw합니다OverflowException.DoubleParse(String, NumberStyles, IFormatProvider)

.NET Core 3.0 이상 버전에서는 데이터 형식 범위를 벗어난 경우 s 예외가 Double throw되지 않습니다. 대부분의 경우 메서드가 Parse(String, NumberStyles, IFormatProvider) 반환 Double.PositiveInfinity 되거나 Double.NegativeInfinity. 그러나 양수 또는 음수 무한대보다 최대값 또는 최소값에 더 가까운 것으로 간주되는 작은 값 Double 집합이 있습니다. 이러한 경우 메서드는 반환 Double.MaxValue 하거나 Double.MinValue.

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

추가 정보

적용 대상