Double.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:
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에 지정된 숫자 값 또는 기호에 해당하는 배정밀도 부동 소수점 숫자입니다.

구현

예외

s이(가) null인 경우

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

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifier 값입니다.

.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.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 해당)은 형식의 Double 범위에 있는 경우 항상 성공적으로 구문 분석됩니다. 나머지 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 매개 변수는 메서드가 GetFormat 형식을 IFormatProviderNumberFormatInfo 해석하는 데 사용되는 문화권별 정보를 제공하는 개체를 반환하는 구현입니다s. 일반적으로 또는 CultureInfo 개체입니다NumberFormatInfo. 가 null 또는 를 NumberFormatInfo 가져올 수 없는 경우 provider 현재 시스템 문화권에 대한 서식 지정 정보가 사용됩니다.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 또는 Double.MaxValueMinValue 문자열 표현을 구문 분석하려고 시도하면 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 을 OverflowExceptionthrow합니다. .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 이하 버전에서 가 데이터 형식 Parse(String, NumberStyles, IFormatProvider) 범위를 Double 벗어나면 s 메서드는 을 OverflowExceptionthrow합니다.

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

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

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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가 숫자 값을 나타내지 않는 경우

styleNumberStyles 값이 아닙니다.

또는

styleAllowHexSpecifier 값입니다.

설명

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

가 데이터 형식 범위를 벗어나면 s 가 보다 작으면 s 메서드가 를 반환하고 Double.PositiveInfinity 가 보다 Double.MinValueDouble.MaxValue크면 s 을 반환 Double.NegativeInfinityDouble 합니다.

적용 대상

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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(String, IFormatProvider)

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에 지정된 숫자 값 또는 기호에 해당하는 배정밀도 부동 소수점 숫자입니다.

구현

예외

s이(가) null인 경우

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 사양에 따라 반올림되거나 NegativeInfinity 필요에 따라 반올림 PositiveInfinity 됩니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

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

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

[ws] [sign] 정수 자릿수[.[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 매개 변수는 메서드가 GetFormat 형식을 IFormatProviderNumberFormatInfo 해석하는 데 사용되는 문화권별 정보를 제공하는 개체를 반환하는 구현입니다s. 일반적으로 또는 CultureInfo 개체입니다NumberFormatInfo. 가 null 또는 를 NumberFormatInfo 가져올 수 없는 경우 provider 현재 시스템 문화권에 대한 서식 지정 정보가 사용됩니다.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도가 손실되어 값이 같지 않을 수 있습니다. 또한 또는 Double.MaxValueDouble.MinValue 문자열 표현을 구문 분석하려고 시도하면 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 을 OverflowExceptionthrow합니다. .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 이하 버전에서 가 데이터 형식 Parse(String, IFormatProvider) 범위를 Double 벗어나면 s 메서드는 을 OverflowExceptionthrow합니다.

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

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

추가 정보

적용 대상

Parse(String)

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에 지정된 숫자 값 또는 기호에 해당하는 배정밀도 부동 소수점 숫자입니다.

예외

s이(가) null인 경우

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

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

예제

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

public ref class Temperature
{
   // Parses the temperature from a string in form
   // [ws][sign]digits['F|'C][ws]
public:
   static Temperature^ Parse( String^ s )
   {
      Temperature^ temp = gcnew Temperature;
      if ( s->TrimEnd(nullptr)->EndsWith( "'F" ) )
      {
         temp->Value = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      if ( s->TrimEnd(nullptr)->EndsWith( "'C" ) )
      {
         temp->Celsius = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      {
         temp->Value = Double::Parse( s );
      }

      return temp;
   }

protected:
   // The value holder
   double m_value;

public:
   property double Value 
   {
      double get()
      {
         return m_value;
      }
      void set( double value )
      {
         m_value = value;
      }
   }

   property double Celsius 
   {
      double get()
      {
         return (m_value - 32.0) / 1.8;
      }
      void set( double value )
      {
         m_value = 1.8 * value + 32.0;
      }
   }
};
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 사양에 따라 반올림되거나 NegativeInfinity 필요에 따라 반올림 PositiveInfinity 됩니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

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

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

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

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

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

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

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

   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 이하 버전에서 가 데이터 형식 Parse(String) 범위를 Double 벗어나면 s 메서드는 을 OverflowExceptionthrow합니다.

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

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

추가 정보

적용 대상

Parse(ReadOnlySpan<Char>, IFormatProvider)

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(ReadOnlySpan<Byte>, IFormatProvider)

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(String, NumberStyles)

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에 지정된 숫자 값 또는 기호에 해당하는 배정밀도 부동 소수점 숫자입니다.

예외

s이(가) null인 경우

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

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

styleNumberStyles 값이 아닙니다.

또는

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

예제

다음 예제에서는 메서드를 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 사양에 따라 반올림되거나 NegativeInfinity 필요에 따라 반올림 PositiveInfinity 됩니다. 이전 버전에서는 .NET Framework 포함하여 너무 큰 값을 구문 분석하여 오류가 발생했습니다.

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

매개 변수는 s 현재 문화권의 NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol또는 을 포함할 NumberFormatInfo.NaNSymbol수 있습니다. 의 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 음수 기호(-) 또는 양수 기호 기호(+)입니다. 플래그를 포함하는 경우 의 시작 부분에 s 표시할 수 있으며 플래그가 포함된 NumberStyles.AllowTrailingSign 경우 styles 끝에 표시할 수 있습니다.styleNumberStyles.AllowLeadingSign 플래그를 포함하는 NumberStyles.AllowParentheses 경우 style 괄호를 사용하여 s 음수 값을 나타낼 수 있습니다.
정수 자릿수 숫자의 정수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 문자열에 fractional-digits 요소가 포함된 경우 정 수 자릿수 요소가 없을 수 있습니다.
, 문화권별 그룹 구분 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 그룹 구분 기호가 NumberStyles.AllowThousandss 나타날 수 있습니다.
. 문화권별 소수점 기호입니다. 플래그가 포함된 경우 style 현재 문화권의 소수점 기호가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.
fractional-digits 숫자의 소수 부분을 지정하는 0에서 9까지의 일련의 숫자입니다. 플래그가 포함된 경우 style 소수 자릿수가 NumberStyles.AllowDecimalPoints 나타날 수 있습니다.
E 값이 지수(공학) 표기법으로 표시됨을 나타내는 "e" 또는 "E" 문자입니다. 매개 변수는 s 플래그를 포함하는 경우 style 지수 표기법으로 NumberStyles.AllowExponent 숫자를 나타낼 수 있습니다.
exponential-digits 지수를 지정하는 0에서 9까지의 일련의 숫자입니다.

참고

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

숫자만 있는 문자열(스타일에 NumberStyles.None 해당)은 형식 범위에 Double 있는 경우 항상 성공적으로 구문 분석됩니다. 나머지 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 매개 변수는 현재 시스템 문화권에 대해 초기화된 개체의 NumberFormatInfo 서식 정보를 사용하여 구문 분석됩니다. 자세한 내용은 CurrentInfo를 참조하세요.

일반적으로 메서드를 Double.Parse 호출 Double.ToString 하여 만든 문자열을 메서드에 전달하면 원래 Double 값이 반환됩니다. 그러나 정밀도 손실로 인해 값이 같지 않을 수 있습니다. 또한 또는 Double.MaxValueDouble.MinValue 문자열 표현을 구문 분석하려고 시도하면 왕복에 실패합니다. .NET Framework 및 .NET Core 2.2 및 이전 버전에서는 을 OverflowExceptionthrow합니다. .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 이하 버전에서 가 데이터 형식 Parse(String, NumberStyles) 범위를 Double 벗어나면 s 메서드는 을 OverflowExceptionthrow합니다.

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

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

추가 정보

적용 대상