共用方式為


Double.Parse 方法

定義

將數位的字串表示轉換為其對等的雙精確度浮點數。

多載

名稱 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 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

Parse(String)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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 及更早版本: s 代表小於 Double.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 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

參數s可包含當前文化的 NumberFormatInfo.PositiveInfinitySymbol、 或NumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol符號。 此字串比較在 .NET Core 3.0 及以後版本中不區分大小寫,但在先前版本(包括 .NET Framework)中則不區分大小寫。 參數 s 也可以是如下形式的字串:

[ws][標誌][整數數字[]]整數數字[.[小數數字]][E[符號]指數數字][ws]

方括弧 ([ 和 ]) 中的元素是選擇性的。 下表描述每個元素。

元素 描述
ws 一系列空格符。
簽署 負號符號 (-) 或正負號符號 (+)。 只能使用前置符號。
整數數字 一系列數位,範圍從 0 到 9,指定數位的整數部分。 整 數數字 的連續可以用分隔符號來劃分。 例如,在某些文化特性中,逗號 (,) 會分隔數千個群組。 如果字串包含小數位元元素,整數數字元素可以不存在。
, 特定文化特性的千位分隔符符號。
. 特定文化特性的小數點符號。
小數數字 一系列數位,範圍從 0 到 9,指定數位的小數部分。
E “e” 或 “E” 字元,表示值是以指數(科學)表示法表示。
指數位數 指定指數的一系列數位範圍從 0 到 9。

s參數是透過 和 NumberStyles.AllowThousands 旗標的組合NumberStyles.Float來解釋的。 這表示允許空格符和千位分隔符,例如,貨幣符號則不允許。 若想更細緻地控制允許在 s 哪些樣式元素中進行解析操作成功,請呼叫 或 Double.Parse(String, NumberStyles) 方法 Double.Parse(String, NumberStyles, IFormatProvider)

s參數是利用物件中NumberFormatInfo格式化資訊來解讀,該物件已為當前文化初始化。 如需詳細資訊,請參閱CurrentInfo。 若要解析字串,使用其他文化的格式資訊,請呼叫 or Double.Parse(String, IFormatProvider)Double.Parse(String, NumberStyles, IFormatProvider) 方法。

通常,如果你傳 Double.Parse 給方法一個由呼叫 Double.ToString 該方法所產生的字串, Double 原始值就會被回傳。 不過,在 .NET Framework 和 .NET Core 2.2 和舊版上,由於精確度遺失,值可能不相等。 此外,嘗試解析 或 Double.MinValueDouble.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 超出資料型態範圍 DoubleParse(String) 該方法會拋 OverflowException出 。

在 .NET Core 3.0 及更新版本中,當 s 超出資料型別範圍 Double 時,不會拋出例外。 在大多數情況下,該方法會回傳 Double.PositiveInfinityDouble.NegativeInfinity。 然而,有一小組被認為更接近 的最大 Double 值或最小值,而非正無窮或負無限大。 在這些情況下,該方法會回傳 Double.MaxValueDouble.MinValue

若在解析操作中遇到參數分 s 隔符,且適用的貨幣或數字分隔符相同,則解析操作假設分隔符為十進位分隔符而非群分隔符。 欲了解更多分離子資訊,請參見 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator及 。

另請參閱

適用於

Parse(ReadOnlySpan<Byte>, IFormatProvider)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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於 中的樣式元素。 典型的指定值是 Float 將 與 結合 AllowThousands

傳回

一個雙精度浮點數,等同於 中 s指定的數值或符號。

例外狀況

snull

s 不代表一個有效格式的數字。

.NET Framework 及 .NET Core 2.2 及更早版本: s 代表小於 Double.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 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

參數 style 定義了允許在解析操作中 s 成功使用風格元素(如空白、數千個分隔符和貨幣符號)。 它必須是列舉中多個位元旗 NumberStyles 標的組合。 以下 NumberStyles 成員不獲支援:

參數s可包含當前文化的 NumberFormatInfo.PositiveInfinitySymbol、 或NumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol符號。 此字串比較在 .NET Core 3.0 及以後版本中不區分大小寫,但在先前版本(包括 .NET Framework)中則不區分大小寫。 根據 的 style值, s 參數也可以呈現如下形式:

[ws][$][符號][整數數字[]]整數數字[[小數數字]][E[符號]指數數字][ws]

方括弧 ([ 和 ]) 中的元素是選擇性的。 下表描述每個元素。

元素 描述
ws 一系列空格符。 如果包含該旗幟,空白可以出現在 的s開頭,如果包含該NumberStyles.AllowTrailingWhite旗,則可以出現在 的結尾stylesNumberStyles.AllowLeadingWhitestyle
$ 特定文化特性的貨幣符號。 它在字串中的位置由NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern當前文化的性質所定義。 當前s文化的貨幣符號可以出現style在包含NumberStyles.AllowCurrencySymbol國旗的情況下。
簽署 負號符號 (-) 或正負號符號 (+)。 如果包含NumberStyles.AllowLeadingSign旗幟,標誌可以出現在 的styles開頭,如果包含NumberStyles.AllowTrailingSign該旗幟,則可以出現在 的結尾sstyle。 若s包含旗標,style則可使用NumberStyles.AllowParentheses括號表示負值。
整數數字 一系列數位,範圍從 0 到 9,指定數位的整數部分。 如果字串包含小數位元元素,整數數字元素可以不存在。
, 特定文化特性的群組分隔符。 當前文化的群組分隔符號可以出現在 style 如果s包含旗NumberStyles.AllowThousands
. 特定文化特性的小數點符號。 當前文化的小數點符號可以出現sstyle在包含NumberStyles.AllowDecimalPoint國旗的情況下。
小數數字 一系列數位,範圍從 0 到 9,指定數位的小數部分。 若style包含NumberStyles.AllowDecimalPoint旗幟,則可出現s小數數字。
E “e” 或 “E” 字元,表示值是以指數(科學)表示法表示。 若s包含style旗標,參數NumberStyles.AllowExponent可用指數符號表示數字。
指數位數 指定指數的一系列數位範圍從 0 到 9。

注意

任何終止的 NUL(U+0000) 字元 s 都會被解析操作忽略,無論參數值 style 為何。

只有數字的字串(對應 NumberStyles.None 於樣式)若在該類型範圍內 Double ,則能成功解析。 剩餘 System.Globalization.NumberStyles 成員控制輸入字串中可能存在但不必須存在的元素。 下表說明個別 NumberStyles 旗標如何影響可能存在於 s中的元素。

NumberStyles 值 除了數字外,允許加入 s 的元素
None 只有 整數數字 元素。
AllowDecimalPoint 小數點(.)和 小數數字 元素。
AllowExponent 表示指數表示法的 「e」 或 「E」 字元。 此旗標本身支援數字 E數字;需要額外旗標才能成功解析包含正負符號及小數點符號等元素的字串。
AllowLeadingWhite 開頭sw 元素。
AllowTrailingWhite 末尾s 元素。
AllowLeadingSign 符號 元素位於 的開頭 s
AllowTrailingSign 符號 元素位於 的結尾 s
AllowParentheses 符號 元素以 括號形式包含數值。
AllowThousands 千位分隔符 (,) 元素。
AllowCurrencySymbol currency ($) 元素。
Currency 所有元素。 然而,無法 s 表示十六進位數或指數符號中的數字。
Float ws 元素位於s開頭或結尾,符號開頭s符號,以及小數點符號(.)。 參數 s 也可以使用指數符號。
Number wssign、千分符(,)和小數點(.)元素。
Any 所有元素。 然而,無法 s 代表十六進位數。

s參數是利用為當前系統文化初始化的物件格式資訊NumberFormatInfo進行解析。 如需詳細資訊,請參閱CurrentInfo

通常,如果你傳 Double.Parse 給方法一個由呼叫 Double.ToString 該方法所產生的字串, Double 原始值就會被回傳。 不過,由於精確度遺失,值可能不相等。 此外,嘗試解析 或 Double.MinValueDouble.MaxValue 的字串表示無法進行往返。 在 .NET Framework 和 .NET Core 2.2 及更早版本中,會拋出一個 OverflowException. 在 .NET Core 3.0 及更新版本中,嘗試MinValueDouble.PositiveInfinityMaxValue解析或嘗試解析 時,它會回傳。Double.NegativeInfinity 下列範例提供圖例。

   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 超出資料型態範圍 DoubleParse(String, NumberStyles) 該方法會拋 OverflowException出 。

在 .NET Core 3.0 及更新版本中,當 s 超出資料型別範圍 Double 時,不會拋出例外。 在大多數情況下,該 Parse(String, NumberStyles) 方法會回傳 Double.PositiveInfinityDouble.NegativeInfinity。 然而,有一小組被認為更接近 的最大 Double 值或最小值,而非正無窮或負無限大。 在這些情況下,該方法會回傳 Double.MaxValueDouble.MinValue

若在解析操作中遇到參數分 s 隔符,且適用的貨幣或數字分隔符相同,則解析操作假設分隔符為十進位分隔符而非群分隔符。 欲了解更多分離子資訊,請參見 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator及 。

另請參閱

適用於

Parse(String, IFormatProvider)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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 及更早版本: s 代表小於 Double.MinValue 或大於 Double.MaxValue 的數字。

範例

下列範例是 Web 窗體的按鈕點選事件處理程式。 它利用屬性 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 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

這種方法的 Parse(String, IFormatProvider) 過載通常用來將可以多種格式化的文字轉換為一個 Double 值。 例如,它可以用來將使用者輸入的文字轉換成 HTML 文字框,轉換為數值。

s參數是透過 和 NumberStyles.AllowThousands 旗標的組合NumberStyles.Float來解釋的。 參數 s 可包含 NumberFormatInfo.PositiveInfinitySymbol、 , NumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 由 指定 provider為文化的符號。 此字串比較在 .NET Core 3.0 及以後版本中不區分大小寫,但在先前版本(包括 .NET Framework)中則不區分大小寫。 參數 s 也可以包含如下形式的字串:

[ws][標誌]整數數字[.[小數數字]][E[符號]指數數字][ws]

選擇性專案會以方括弧 ([ 和 ]) 框住。 包含「digits」 一詞的元素包含一系列從 0 到 9 的數位字元。

元素 描述
ws 一系列空格符。
簽署 負號符號 (-) 或正負號符號 (+)。
整數數字 一系列數位,範圍從 0 到 9,指定數位的整數部分。 整 數數字 的連續可以用分隔符號來劃分。 例如,在某些文化特性中,逗號 (,) 會分隔數千個群組。 如果字串包含小數位元元素,整數數字元素可以不存在。
. 特定文化特性的小數點符號。
小數數字 一系列數位,範圍從 0 到 9,指定數位的小數部分。
E “e” 或 “E” 字元,表示值是以指數(科學)表示法表示。
指數位數 指定指數的一系列數位範圍從 0 到 9。

欲了解更多關於數字格式的資訊,請參閱 格式類型 主題。

參數 provider 是一個 IFormatProvider 實作,其 GetFormat 方法回傳一個 NumberFormatInfo 物件,提供用於解讀格式 s的文化特定資訊。 通常,它是 a NumberFormatInfoCultureInfo 受詞。 若 provider 無法取得 is null 或 a NumberFormatInfo ,則會使用當前系統文化的格式資訊。

通常,如果你傳 Double.Parse 給方法一個由呼叫 Double.ToString 該方法所產生的字串, Double 原始值就會被回傳。 不過,由於精確度遺失,值可能不相等。 此外,嘗試解析 或 Double.MinValueDouble.MaxValue 的字串表示無法進行往返。 在 .NET Framework 和 .NET Core 2.2 及更早版本中,會拋出一個 OverflowException. 在 .NET Core 3.0 及更新版本中,嘗試MinValueDouble.PositiveInfinityMaxValue解析或嘗試解析 時,它會回傳。Double.NegativeInfinity 下列範例提供圖例。

   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 超出資料型態範圍 DoubleParse(String, IFormatProvider) 該方法會拋 OverflowException出 。

在 .NET Core 3.0 及更新版本中,當 s 超出資料型別範圍 Double 時,不會拋出例外。 在大多數情況下,該 Parse(String, IFormatProvider) 方法會回傳 Double.PositiveInfinityDouble.NegativeInfinity。 然而,有一小組被認為更接近 的最大 Double 值或最小值,而非正無窮或負無限大。 在這些情況下,該方法會回傳 Double.MaxValueDouble.MinValue

若在解析操作中遇到參數分 s 隔符,且適用的貨幣或數字分隔符相同,則解析操作假設分隔符為十進位分隔符而非群分隔符。 欲了解更多分離子資訊,請參見 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator及 。

另請參閱

適用於

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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於 中的樣式元素。 典型的指定值是 FloatAllowThousands結合。

provider
IFormatProvider

一個提供關於 s的文化特定格式資訊的物件。

傳回

一個雙精度浮點數,等同於 中 s指定的數值或符號。

實作

例外狀況

s 不代表數值。

style 不是一個 NumberStyles 數值。

-或-

style 是 的 AllowHexSpecifier 價值。

備註

在 .NET Core 3.0 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

s 超出資料型別範圍Double,則若 s 小於 且 sDouble.MinValueDouble.PositiveInfinity 大於 Double.MaxValue,則回傳 。Double.NegativeInfinity

適用於

Parse(String, NumberStyles, IFormatProvider)

來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
Double.cs
來源:
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於 中的樣式元素。 典型的指定值是 FloatAllowThousands結合。

provider
IFormatProvider

一個提供關於 s的文化特定格式資訊的物件。

傳回

一個雙精度浮點數,等同於 中 s指定的數值或符號。

實作

例外狀況

snull

s 不代表數值。

style 不是一個 NumberStyles 數值。

-或-

style 是 的 AllowHexSpecifier 價值。

.NET Framework 及 .NET Core 2.2 及更早版本: s 代表小於 Double.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 及之後版本中,過大無法表示的數值會被四捨五入到 PositiveInfinityNegativeInfinity 依照 IEEE 754 規範的要求進行。 在舊版中,包括 .NET Framework,剖析的值太大而無法表示導致失敗。

參數 style 定義了允許在解析操作中 s 成功使用風格元素(如空白、數千個分隔符和貨幣符號)。 它必須是列舉中多個位元旗 NumberStyles 標的組合。 以下 NumberStyles 成員不獲支援:

參數 s 可包含 NumberFormatInfo.PositiveInfinitySymbol、 , NumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol 由 指定 provider為文化的符號。 此字串比較在 .NET Core 3.0 及以後版本中不區分大小寫,但在先前版本(包括 .NET Framework)中則不區分大小寫。 根據 的 style值, s 參數也可以呈現如下形式:

[ws][$] [符號][整數數字,]整數數字[.[小數數字]][E[符號]指數數字][ws]

以方括弧 ([ 和 ]) 框架的項目是選擇性的。 下表描述每個元素。

元素 描述
ws 一系列空格符。 如果包含該旗幟,空白可以出現在 的s開頭,如果包含該NumberStyles.AllowTrailingWhite旗,則可以出現在 的結尾stylesNumberStyles.AllowLeadingWhitestyle
$ 特定文化特性的貨幣符號。 它在字串中的位置由NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern當前文化的性質所定義。 當前s文化的貨幣符號可以出現style在包含NumberStyles.AllowCurrencySymbol國旗的情況下。
簽署 負號符號 (-) 或正負號符號 (+)。 如果包含NumberStyles.AllowLeadingSign旗幟,標誌可以出現在 的styles開頭,如果包含NumberStyles.AllowTrailingSign該旗幟,則可以出現在 的結尾sstyle。 若s包含旗標,style則可使用NumberStyles.AllowParentheses括號表示負值。
整數數字 一系列數位,範圍從 0 到 9,指定數位的整數部分。 如果字串包含小數位元元素,整數數字元素可以不存在。
, 特定文化特性的群組分隔符。 當前文化的群組分隔符號可以出現在 style 如果s包含旗NumberStyles.AllowThousands
. 特定文化特性的小數點符號。 當前文化的小數點符號可以出現sstyle在包含NumberStyles.AllowDecimalPoint國旗的情況下。
小數數字 一系列數位,範圍從 0 到 9,指定數位的小數部分。 若style包含NumberStyles.AllowDecimalPoint旗幟,則可出現s小數數字。
E “e” 或 “E” 字元,表示值是以指數(科學)表示法表示。 若s包含style旗標,參數NumberStyles.AllowExponent可用指數符號表示數字。
指數位數 指定指數的一系列數位範圍從 0 到 9。

注意

任何終止的 NUL(U+0000) 字元 s 都會被解析操作忽略,無論參數值 style 為何。

只有數字的字串(對應 NumberStyles.None 於樣式)若在該類型範圍內 Double ,則能成功解析。 剩餘 System.Globalization.NumberStyles 成員控制輸入字串中可能存在但不必須存在的元素。 下表說明個別 NumberStyles 旗標如何影響可能存在於 s中的元素。

NumberStyles 值 除了數字外,允許加入 s 的元素
None 只有 整數數字 元素。
AllowDecimalPoint 小數點(.)和 小數數字 元素。
AllowExponent 表示指數表示法的 「e」 或 「E」 字元。 此旗標本身支援數字 E數字;需要額外旗標才能成功解析包含正負符號及小數點符號等元素的字串。
AllowLeadingWhite 開頭sw 元素。
AllowTrailingWhite 末尾s 元素。
AllowLeadingSign 符號 元素位於 的開頭 s
AllowTrailingSign 符號 元素位於 的結尾 s
AllowParentheses 符號 元素以 括號形式包含數值。
AllowThousands 千位分隔符 (,) 元素。
AllowCurrencySymbol currency ($) 元素。
Currency 所有元素。 然而,無法 s 表示十六進位數或指數符號中的數字。
Float ws 元素位於s開頭或結尾,符號開頭s符號,以及小數點符號(.)。 參數 s 也可以使用指數符號。
Number wssign、千分符(,)和小數點(.)元素。
Any 所有元素。 然而,無法 s 代表十六進位數。

參數 provider 是一個 IFormatProvider 實作,其 GetFormat 方法回傳一個 NumberFormatInfo 物件,提供用於解讀格式 s的文化特定資訊。 通常,它是 a NumberFormatInfoCultureInfo 受詞。 若 provider 無法取得 is null 或 a NumberFormatInfo ,則會使用當前系統文化的格式資訊。

通常,如果你傳 Double.Parse 給方法一個由呼叫 Double.ToString 該方法所產生的字串, Double 原始值就會被回傳。 不過,由於精確度遺失,值可能不相等。 此外,嘗試解析 或 MinValueDouble.MaxValue 的字串表示無法進行往返。 在 .NET Framework 和 .NET Core 2.2 及更早版本中,會拋出一個 OverflowException. 在 .NET Core 3.0 及更新版本中,嘗試MinValueDouble.PositiveInfinityMaxValue解析或嘗試解析 時,它會回傳。Double.NegativeInfinity 下列範例提供圖例。

   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 超出資料型態範圍 DoubleParse(String, NumberStyles, IFormatProvider) 該方法會拋 OverflowException出 。

在 .NET Core 3.0 及更新版本中,當 s 超出資料型別範圍 Double 時,不會拋出例外。 在大多數情況下,該 Parse(String, NumberStyles, IFormatProvider) 方法會回傳 Double.PositiveInfinityDouble.NegativeInfinity。 然而,有一小組被認為更接近 的最大 Double 值或最小值,而非正無窮或負無限大。 在這些情況下,該方法會回傳 Double.MaxValueDouble.MinValue

若在解析操作中遇到參數分 s 隔符,且適用的貨幣或數字分隔符相同,則解析操作假設分隔符為十進位分隔符而非群分隔符。 欲了解更多分離子資訊,請參見 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparator及 。

另請參閱

適用於