Double.Parse 方法 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将数字的字符串表示形式转换为等效的双精度浮点数。
重载
| Parse(String) | 将数字的字符串表示形式转换为等效的双精度浮点数。 | 
| Parse(ReadOnlySpan<Byte>, IFormatProvider) | 将 UTF-8 字符的范围分析为值。 | 
| Parse(ReadOnlySpan<Char>, IFormatProvider) | 将字符的范围分析为值。 | 
| Parse(String, NumberStyles) | 将指定样式中的数字的字符串表示形式转换为等效的双精度浮点数。 | 
| Parse(String, IFormatProvider) | 将指定区域性特定格式的数字的字符串表示形式转换为等效的双精度浮点数。 | 
| Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) | 将 UTF-8 字符的范围分析为值。 | 
| Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) | 将包含指定样式和区域性特定格式的数字的字符串表示形式的字符范围转换为等效的双精度浮点数。 | 
| Parse(String, NumberStyles, IFormatProvider) | 将指定样式和区域性特定格式的数字的字符串表示形式转换为等效的双精度浮点数。 | 
注解
在 .NET Core 3.0 及更高版本中,无法表示的值舍入为 IEEE 754 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
Parse(String)
- Source:
- Double.cs
- Source:
- Double.cs
- Source:
- Double.cs
将数字的字符串表示形式转换为等效的双精度浮点数。
public:
 static double Parse(System::String ^ s);public static double Parse (string s);static member Parse : string -> doublePublic Shared Function Parse (s As String) As Double参数
- s
- String
包含要转换的数字的字符串。
返回
与 s中指定的数值或符号等效的双精度浮点数。
例外
              s
              null。
              s 不以有效格式表示数字。
仅 .NET Framework 和 .NET Core 2.2 及更低版本:s 表示小于 double.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 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
              s 参数可以包含当前区域性的 NumberFormatInfo.PositiveInfinitySymbol、NumberFormatInfo.NegativeInfinitySymbol、NumberFormatInfo.NaNSymbol或格式字符串:
[ws][符号][整型数字[,]]整型数字[.[分数数字]][E[符号]指数数字][ws]
方括号 ([ 和 ]) 中的元素是可选的。 下表描述了每个元素。
| 元素 | 描述 | 
|---|---|
| ws | 一系列空白字符。 | 
| 签名 | 负号符号(-)或正符号(+)。 只能使用前导符号。 | 
| 整型数字 | 一系列数字,范围从 0 到 9,用于指定数字的整部分。 整型数字 的运行可以按组分隔符进行分区。 例如,在某些区域性中,逗号 (,) 分隔成千个组。 如果字符串包含 小数位数 元素,则 整型数字 元素可能不存在。 | 
| , | 区域性特定的千位分隔符符号。 | 
| . | 区域性特定的小数点符号。 | 
| 小数位数 | 一系列数字,范围从 0 到 9,指定数字的小数部分。 | 
| E | “e”或“E”字符,指示该值以指数(科学)表示法表示。 | 
| 指数位数 | 一系列数字,范围从 0 到 9,用于指定指数。 | 
              s 参数使用 NumberStyles.Float 和 NumberStyles.AllowThousands 标志的组合进行解释。 这意味着允许空格和千位分隔符,例如,货币符号不是。 若要更好地控制分析操作成功 s 允许哪些样式元素,请调用 Double.Parse(String, NumberStyles) 或 Double.Parse(String, NumberStyles, IFormatProvider) 方法。
              s 参数使用为当前区域性初始化的 NumberFormatInfo 对象中的格式设置信息进行解释。 有关详细信息,请参阅 CurrentInfo。 若要使用其他区域性的格式设置信息分析字符串,请调用 Double.Parse(String, IFormatProvider) 或 Double.Parse(String, NumberStyles, IFormatProvider) 方法。
通常,如果将 Double.Parse 方法传递给通过调用 Double.ToString 方法创建的字符串,则返回原始 Double 值。 但是,在 .NET Framework 和 .NET Core 2.2 及更低版本上,由于精度损失,值可能不相等。 此外,尝试分析 Double.MinValue 或 Double.MaxValue 的字符串表示形式无法往返。 在 .NET Framework 和 .NET Core 2.2 及早期版本中,它引发 OverflowException。 以下示例提供了一个插图。
   string value;
   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System
[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."
    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."
    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."
    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String
value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308
在 .NET Framework 和 .NET Core 2.2 及更早版本中,如果 s 与 Double 数据类型的范围不同,Parse(String) 方法将引发 OverflowException。
在 .NET Core 3.0 及更高版本中,当 s 超过 Double 数据类型的范围时,不会引发异常。 在大多数情况下,该方法将返回 Double.PositiveInfinity 或 Double.NegativeInfinity。 但是,有一小组值被认为更接近 Double 的最大值或最小值,而不是正或负无穷大。 在这些情况下,该方法返回 Double.MaxValue 或 Double.MinValue。
如果在分析操作期间 s 参数中遇到分隔符,并且适用的货币或数字小数和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparator、NumberDecimalSeparator、CurrencyGroupSeparator和 NumberGroupSeparator。
另请参阅
适用于
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 -> doublePublic Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Double参数
- utf8Text
- ReadOnlySpan<Byte>
要分析的 UTF-8 字符的范围。
- provider
- IFormatProvider
一个对象,提供有关 utf8Text的区域性特定格式设置信息。
返回
分析 utf8Text的结果。
实现
适用于
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Source:
- Double.cs
- Source:
- Double.cs
- Source:
- Double.cs
将字符的范围分析为值。
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 -> doublePublic Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Double参数
- s
- ReadOnlySpan<Char>
要分析的字符范围。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
返回
分析 s的结果。
实现
适用于
Parse(String, NumberStyles)
- Source:
- Double.cs
- Source:
- Double.cs
- Source:
- Double.cs
将指定样式中的数字的字符串表示形式转换为等效的双精度浮点数。
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 -> doublePublic Shared Function Parse (s As String, style As NumberStyles) As Double参数
- s
- String
包含要转换的数字的字符串。
- style
- NumberStyles
枚举值的按位组合,指示 s中可以存在的样式元素。 要指定的典型值是 Float 与 AllowThousands的组合。
返回
与 s中指定的数值或符号等效的双精度浮点数。
例外
              s
              null。
              s 不以有效格式表示数字。
仅 .NET Framework 和 .NET Core 2.2 及更低版本:s 表示小于 double.MinValue 或大于 Double.MaxValue的数字。
示例
以下示例使用 Parse(String, NumberStyles) 方法通过 en-US 区域性分析 Double 值的字符串表示形式。
public static void Main()
{
   // Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
   string value;
   NumberStyles styles;
   // Parse a string in exponential notation with only the AllowExponent flag.
   value = "-1.063E-02";
   styles = NumberStyles.AllowExponent;
   ShowNumericValue(value, styles);
   // Parse a string in exponential notation
   // with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent | NumberStyles.Number;
   ShowNumericValue(value, styles);
   // Parse a currency value with leading and trailing white space, and
   // white space after the U.S. currency symbol.
   value = " $ 6,164.3299  ";
   styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
   ShowNumericValue(value, styles);
   // Parse negative value with thousands separator and decimal.
   value = "(4,320.64)";
   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float;
   ShowNumericValue(value, styles);
   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float | NumberStyles.AllowThousands;
   ShowNumericValue(value, styles);
}
private static void ShowNumericValue(string value, NumberStyles styles)
{
   double number;
   try
   {
      number = Double.Parse(value, styles);
      Console.WriteLine("Converted '{0}' using {1} to {2}.",
                        value, styles.ToString(), number);
   }
   catch (FormatException)
   {
      Console.WriteLine("Unable to parse '{0}' with styles {1}.",
                        value, styles.ToString());
   }
   Console.WriteLine();
}
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
open System
open System.Globalization
open System.Threading
let showNumericValue (value: string) (styles: NumberStyles) =
    try
        let number = Double.Parse(value, styles)
        printfn $"Converted '{value}' using {styles} to {number}."
    with :? FormatException ->
        printfn $"Unable to parse '{value}' with styles {styles}."
    printfn ""
[<EntryPoint>]
let main _ =
    // Set current thread culture to en-US.
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"
    // Parse a string in exponential notation with only the AllowExponent flag.
    let value = "-1.063E-02"
    let styles = NumberStyles.AllowExponent
    showNumericValue value styles
    // Parse a string in exponential notation
    // with the AllowExponent and Number flags.
    let styles = NumberStyles.AllowExponent ||| NumberStyles.Number
    showNumericValue value styles
    // Parse a currency value with leading and trailing white space, and
    // white space after the U.S. currency symbol.
    let value = " $ 6,164.3299  "
    let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
    showNumericValue value styles
    // Parse negative value with thousands separator and decimal.
    let value = "(4,320.64)"
    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float
    showNumericValue value styles
    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
    showNumericValue value styles
    0
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Public Sub Main()
   ' Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         
   Dim value As String
   Dim styles As NumberStyles
   
   ' Parse a string in exponential notation with only the AllowExponent flag. 
   value = "-1.063E-02"
   styles = NumberStyles.AllowExponent
   ShowNumericValue(value, styles) 
   
   ' Parse a string in exponential notation
   ' with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent Or NumberStyles.Number
   ShowNumericValue(value, styles)
   ' Parse a currency value with leading and trailing white space, and
   ' white space after the U.S. currency symbol.
   value = " $ 6,164.3299  "
   styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
   ShowNumericValue(value, styles)
   
   ' Parse negative value with thousands separator and decimal.
   value = "(4,320.64)"
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float 
   ShowNumericValue(value, styles)
   
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float Or NumberStyles.AllowThousands
   ShowNumericValue(value, styles)
End Sub
Private Sub ShowNumericValue(value As String, styles As NumberStyles)
   Dim number As Double
   Try
      number = Double.Parse(value, styles)
      Console.WriteLine("Converted '{0}' using {1} to {2}.", _
                        value, styles.ToString(), number)
   Catch e As FormatException
      Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
                        value, styles.ToString())
   End Try
   Console.WriteLine()                           
End Sub
' The example displays the following output to the console:
'    Unable to parse '-1.063E-02' with styles AllowExponent.
'    
'    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'    
'    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
'    
'    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'    
'    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
注解
在 .NET Core 3.0 及更高版本中,无法表示的值舍入为 IEEE 754 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
              style 参数定义允许在分析操作成功 s 参数中允许的样式元素(如空格、千位分隔符和货币符号)。 它必须是 NumberStyles 枚举中的位标志的组合。 不支持以下 NumberStyles 成员:
              s 参数可以包含当前区域性的 NumberFormatInfo.PositiveInfinitySymbol、NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol。 根据 style的值,还可以采用以下形式:
[ws][$][符号][整型数字[,]]整型数字[.[分数位数]][E[符号]指数数字][ws]
方括号 ([ 和 ]) 中的元素是可选的。 下表描述了每个元素。
| 元素 | 描述 | 
|---|---|
| ws | 一系列空白字符。 如果 style包含 NumberStyles.AllowLeadingWhite 标志,则空格可能出现在s的开头,如果style包含 NumberStyles.AllowTrailingWhite 标志,则它将显示在s末尾。 | 
| $ | 区域性特定的货币符号。 字符串中的位置由当前区域性的 NumberFormatInfo.CurrencyNegativePattern 和 NumberFormatInfo.CurrencyPositivePattern 属性定义。 如果 style包含 NumberStyles.AllowCurrencySymbol 标志,则当前区域性的货币符号可以出现在s中。 | 
| 签名 | 负号符号(-)或正符号(+)。 如果 style包含 NumberStyles.AllowLeadingSign 标志,则符号可以在s开头显示,如果style包含 NumberStyles.AllowTrailingSign 标志,则它将显示在s末尾。 如果style包含 NumberStyles.AllowParentheses 标志,则可以在s中使用括号来指示负值。 | 
| 整型数字 | 一系列数字,范围从 0 到 9,用于指定数字的整部分。 如果字符串包含 小数位数 元素,则 整型数字 元素可能不存在。 | 
| , | 区域性特定的组分隔符。 如果 style包含 NumberStyles.AllowThousands 标志,则当前区域性的组分隔符可以出现在s中 | 
| . | 区域性特定的小数点符号。 如果 style包含 NumberStyles.AllowDecimalPoint 标志,则当前区域性的小数点符号可以出现在s中。 | 
| 小数位数 | 一系列数字,范围从 0 到 9,指定数字的小数部分。 如果 style包含 NumberStyles.AllowDecimalPoint 标志,则可以在s中显示小数位数。 | 
| E | “e”或“E”字符,指示该值以指数(科学)表示法表示。 如果 style包含 NumberStyles.AllowExponent 标志,s参数可以表示指数表示法中的数字。 | 
| 指数位数 | 一系列数字,范围从 0 到 9,用于指定指数。 | 
注意
无论 style 参数的值如何,分析操作都会忽略 s 中任何终止的 NUL (U+0000) 字符。
仅包含数字(对应于 NumberStyles.None 样式)的字符串在 Double 类型范围内时始终成功分析。 其余 System.Globalization.NumberStyles 成员控制可能存在的元素,但不需要在输入字符串中存在。 下表指示单个 NumberStyles 标志如何影响 s中可能存在的元素。
| NumberStyles 值 | 除数字外, s允许的元素 | 
|---|---|
| None | 仅 整型数字 元素。 | 
| AllowDecimalPoint | 小数点(.)和 小数位数 元素。 | 
| AllowExponent | 指示指数表示法的“e”或“E”字符。 此标志本身支持 数字形式的值,E位;需要其他标志才能成功分析包含正数或负号和小数点符号等元素的字符串。 | 
| AllowLeadingWhite | s开头的 ws 元素。 | 
| AllowTrailingWhite | s末尾的 ws 元素。 | 
| AllowLeadingSign | s开头的 符号 元素。 | 
| AllowTrailingSign | s末尾的 符号 元素。 | 
| AllowParentheses | 符号 元素,以括住数值的括号形式。 | 
| AllowThousands | 千位分隔符 (,) 元素。 | 
| AllowCurrencySymbol | currency ($) 元素。 | 
| Currency | 所有元素。 但是, s不能表示十六进制数或指数表示法中的数字。 | 
| Float | ws 元素位于 s的开头或末尾,符号s开头,以及小数点(.)符号。s参数也可以使用指数表示法。 | 
| Number | ws、sign、千位分隔符(、)和小数点(.)元素。 | 
| Any | 所有元素。 但是, s不能表示十六进制数。 | 
              s 参数是使用为当前系统区域性初始化的 NumberFormatInfo 对象中的格式信息进行分析的。 有关详细信息,请参阅 CurrentInfo。
通常,如果将 Double.Parse 方法传递给通过调用 Double.ToString 方法创建的字符串,则返回原始 Double 值。 但是,由于精度损失,值可能不相等。 此外,尝试分析 Double.MinValue 或 Double.MaxValue 的字符串表示形式无法往返。 在 .NET Framework 和 .NET Core 2.2 及早期版本中,它引发 OverflowException。 在 .NET Core 3.0 及更高版本中,如果尝试分析 MinValue 或 Double.PositiveInfinity 尝试分析 MaxValue,则返回 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 与 Double 数据类型的范围不同,Parse(String, NumberStyles) 方法将引发 OverflowException。
在 .NET Core 3.0 及更高版本中,当 s 超过 Double 数据类型的范围时,不会引发异常。 在大多数情况下,Parse(String, NumberStyles) 方法将返回 Double.PositiveInfinity 或 Double.NegativeInfinity。 但是,有一小组值被认为更接近 Double 的最大值或最小值,而不是正或负无穷大。 在这些情况下,该方法返回 Double.MaxValue 或 Double.MinValue。
如果在分析操作期间 s 参数中遇到分隔符,并且适用的货币或数字小数和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparator、NumberDecimalSeparator、CurrencyGroupSeparator和 NumberGroupSeparator。
另请参阅
- ToString()
- TryParse
- 分析 .NET 中的数值字符串
适用于
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 -> doublePublic 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 及更低版本:s 表示小于 double.MinValue 或大于 Double.MaxValue的数字。
示例
以下示例是 Web 窗体的按钮单击事件处理程序。 它使用 HttpRequest.UserLanguages 属性返回的数组来确定用户的区域设置。 然后,它会实例化与该区域设置对应的 CultureInfo 对象。 然后,将属于该 CultureInfo 对象的 NumberFormatInfo 对象传递给 Parse(String, IFormatProvider) 方法,将用户的输入转换为 Double 值。
protected void OkToDouble_Click(object sender, EventArgs e)
{
    string locale;
    double number;
    CultureInfo culture;
    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;
    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;
    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);
    // Convert user input from a string to a number
    try
    {
        number = Double.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (OverflowException)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDouble_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDouble.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Double
   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub
   
   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub
   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)
   ' Convert user input from a string to a number
   Try
      number = Double.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try
   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub
注解
在 .NET Core 3.0 及更高版本中,无法表示的值舍入为 IEEE 754 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
Parse(String, IFormatProvider) 方法的此重载通常用于将可通过多种方式格式化的文本转换为 Double 值。 例如,它可用于将用户输入的文本转换为 HTML 文本框的数值。
              s 参数使用 NumberStyles.Float 和 NumberStyles.AllowThousands 标志的组合进行解释。 
              s 参数可以包含由 provider指定的区域性的 NumberFormatInfo.PositiveInfinitySymbol、NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol,也可以包含格式的字符串:
[ws][符号]整型数字[.[分数数字][E[符号]指数数字][ws]
可选元素采用方括号([ 和 ])框架。 包含术语“digits”的元素由一系列介于 0 到 9 的数字字符组成。
| 元素 | 描述 | 
|---|---|
| ws | 一系列空白字符。 | 
| 签名 | 负号符号(-)或正符号(+)。 | 
| 整型数字 | 一系列数字,范围从 0 到 9,用于指定数字的整部分。 整型数字 的运行可以按组分隔符进行分区。 例如,在某些区域性中,逗号 (,) 分隔成千个组。 如果字符串包含 小数位数 元素,则 整型数字 元素可能不存在。 | 
| . | 区域性特定的小数点符号。 | 
| 小数位数 | 一系列数字,范围从 0 到 9,指定数字的小数部分。 | 
| E | “e”或“E”字符,指示该值以指数(科学)表示法表示。 | 
| 指数位数 | 一系列数字,范围从 0 到 9,用于指定指数。 | 
有关数字格式的详细信息,请参阅 格式设置类型 主题。
              provider 参数是一个 IFormatProvider 实现,其 GetFormat 方法返回一个 NumberFormatInfo 对象,该对象提供解释 s格式时使用的区域性特定信息。 通常,它是 NumberFormatInfo 或 CultureInfo 对象。 如果 providernull 或无法获取 NumberFormatInfo,则使用当前系统区域性的格式设置信息。
通常,如果将 Double.Parse 方法传递给通过调用 Double.ToString 方法创建的字符串,则返回原始 Double 值。 但是,由于精度损失,值可能不相等。 此外,尝试分析 Double.MinValue 或 Double.MaxValue 的字符串表示形式无法往返。 在 .NET Framework 和 .NET Core 2.2 及早期版本中,它引发 OverflowException。 在 .NET Core 3.0 及更高版本中,如果尝试分析 MinValue 或 Double.PositiveInfinity 尝试分析 MaxValue,则返回 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 与 Double 数据类型的范围不同,Parse(String, IFormatProvider) 方法将引发 OverflowException。
在 .NET Core 3.0 及更高版本中,当 s 超过 Double 数据类型的范围时,不会引发异常。 在大多数情况下,Parse(String, IFormatProvider) 方法将返回 Double.PositiveInfinity 或 Double.NegativeInfinity。 但是,有一小组值被认为更接近 Double 的最大值或最小值,而不是正或负无穷大。 在这些情况下,该方法返回 Double.MaxValue 或 Double.MinValue。
如果在分析操作期间 s 参数中遇到分隔符,并且适用的货币或数字小数和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparator、NumberDecimalSeparator、CurrencyGroupSeparator和 NumberGroupSeparator。
另请参阅
- ToString()
- TryParse
- 分析 .NET 中的数值字符串
适用于
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 -> doublePublic Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double参数
- utf8Text
- ReadOnlySpan<Byte>
要分析的 UTF-8 字符的范围。
- style
- NumberStyles
              utf8Text中可以存在的数字样式的按位组合。
- provider
- IFormatProvider
一个对象,提供有关 utf8Text的区域性特定格式设置信息。
返回
分析 utf8Text的结果。
实现
适用于
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- Source:
- Double.cs
- Source:
- Double.cs
- Source:
- Double.cs
将包含指定样式和区域性特定格式的数字的字符串表示形式的字符范围转换为等效的双精度浮点数。
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 -> doublePublic 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中可以存在的样式元素。  要指定的典型值 Float 与 AllowThousands结合使用。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
返回
与 s中指定的数值或符号等效的双精度浮点数。
实现
例外
              s 不表示数值。
注解
在 .NET Core 3.0 及更高版本中,无法表示的值舍入为 IEEE 754 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
如果 s 超出 Double 数据类型的范围,则如果 s 小于 Double.MinValue,则该方法返回 Double.NegativeInfinity;如果 s 大于 Double.MaxValue,则返回 Double.PositiveInfinity。
适用于
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 -> doublePublic Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Double参数
- s
- String
包含要转换的数字的字符串。
- style
- NumberStyles
枚举值的按位组合,指示 s中可以存在的样式元素。 要指定的典型值 Float 与 AllowThousands结合使用。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
返回
与 s中指定的数值或符号等效的双精度浮点数。
实现
例外
              s
              null。
              s 不表示数值。
仅 .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 及更高版本中,无法表示的值舍入为 IEEE 754 规范所需的 PositiveInfinity 或 NegativeInfinity。 在早期版本中(包括 .NET Framework)中,分析的值太大而无法表示导致失败。
              style 参数定义允许在分析操作成功 s 参数中允许的样式元素(如空格、千位分隔符和货币符号)。 它必须是 NumberStyles 枚举中的位标志的组合。 不支持以下 NumberStyles 成员:
              s 参数可以包含由 provider指定的区域性的 NumberFormatInfo.PositiveInfinitySymbol、NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol。 根据 style的值,还可以采用以下形式:
[ws][$][符号][整型数字,]整型数字[.[小数位数]][E[符号]指数数字][ws]
方括号 ([ 和 ]) 中框架的元素是可选的。 下表描述了每个元素。
| 元素 | 描述 | 
|---|---|
| ws | 一系列空白字符。 如果 style包含 NumberStyles.AllowLeadingWhite 标志,则空格可能出现在s的开头,如果style包含 NumberStyles.AllowTrailingWhite 标志,则它将显示在s末尾。 | 
| $ | 区域性特定的货币符号。 字符串中的位置由当前区域性的 NumberFormatInfo.CurrencyNegativePattern 和 NumberFormatInfo.CurrencyPositivePattern 属性定义。 如果 style包含 NumberStyles.AllowCurrencySymbol 标志,则当前区域性的货币符号可以出现在s中。 | 
| 签名 | 负号符号(-)或正符号(+)。 如果 style包含 NumberStyles.AllowLeadingSign 标志,则符号可以在s开头显示,如果style包含 NumberStyles.AllowTrailingSign 标志,则它将显示在s末尾。 如果style包含 NumberStyles.AllowParentheses 标志,则可以在s中使用括号来指示负值。 | 
| 整型数字 | 一系列数字,范围从 0 到 9,用于指定数字的整部分。 如果字符串包含 小数位数 元素,则 整型数字 元素可能不存在。 | 
| , | 区域性特定的组分隔符。 如果 style包含 NumberStyles.AllowThousands 标志,则当前区域性的组分隔符可以出现在s中 | 
| . | 区域性特定的小数点符号。 如果 style包含 NumberStyles.AllowDecimalPoint 标志,则当前区域性的小数点符号可以出现在s中。 | 
| 小数位数 | 一系列数字,范围从 0 到 9,指定数字的小数部分。 如果 style包含 NumberStyles.AllowDecimalPoint 标志,则可以在s中显示小数位数。 | 
| E | “e”或“E”字符,指示该值以指数(科学)表示法表示。 如果 style包含 NumberStyles.AllowExponent 标志,s参数可以表示指数表示法中的数字。 | 
| 指数位数 | 一系列数字,范围从 0 到 9,用于指定指数。 | 
注意
无论 style 参数的值如何,分析操作都会忽略 s 中任何终止的 NUL (U+0000) 字符。
仅包含数字(对应于 NumberStyles.None 样式)的字符串在 Double 类型范围内时始终成功分析。 其余 System.Globalization.NumberStyles 成员控制可能存在的元素,但不需要在输入字符串中存在。 下表指示单个 NumberStyles 标志如何影响 s中可能存在的元素。
| NumberStyles 值 | 除数字外, s允许的元素 | 
|---|---|
| None | 仅 整型数字 元素。 | 
| AllowDecimalPoint | 小数点(.)和 小数位数 元素。 | 
| AllowExponent | 指示指数表示法的“e”或“E”字符。 此标志本身支持 数字形式的值,E位;需要其他标志才能成功分析包含正数或负号和小数点符号等元素的字符串。 | 
| AllowLeadingWhite | s开头的 ws 元素。 | 
| AllowTrailingWhite | s末尾的 ws 元素。 | 
| AllowLeadingSign | s开头的 符号 元素。 | 
| AllowTrailingSign | s末尾的 符号 元素。 | 
| AllowParentheses | 符号 元素,以括住数值的括号形式。 | 
| AllowThousands | 千位分隔符 (,) 元素。 | 
| AllowCurrencySymbol | currency ($) 元素。 | 
| Currency | 所有元素。 但是, s不能表示十六进制数或指数表示法中的数字。 | 
| Float | ws 元素位于 s的开头或末尾,符号s开头,以及小数点(.)符号。s参数也可以使用指数表示法。 | 
| Number | ws、sign、千位分隔符(、)和小数点(.)元素。 | 
| Any | 所有元素。 但是, s不能表示十六进制数。 | 
              provider 参数是一个 IFormatProvider 实现,其 GetFormat 方法返回一个 NumberFormatInfo 对象,该对象提供解释 s格式时使用的区域性特定信息。 通常,它是 NumberFormatInfo 或 CultureInfo 对象。 如果 providernull 或无法获取 NumberFormatInfo,则使用当前系统区域性的格式设置信息。
通常,如果将 Double.Parse 方法传递给通过调用 Double.ToString 方法创建的字符串,则返回原始 Double 值。 但是,由于精度损失,值可能不相等。 此外,尝试分析 MinValue 或 Double.MaxValue 的字符串表示形式无法往返。 在 .NET Framework 和 .NET Core 2.2 及早期版本中,它引发 OverflowException。 在 .NET Core 3.0 及更高版本中,如果尝试分析 MinValue 或 Double.PositiveInfinity 尝试分析 MaxValue,则返回 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 与 Double 数据类型的范围不同,Parse(String, NumberStyles, IFormatProvider) 方法将引发 OverflowException。
在 .NET Core 3.0 及更高版本中,当 s 超过 Double 数据类型的范围时,不会引发异常。 在大多数情况下,Parse(String, NumberStyles, IFormatProvider) 方法将返回 Double.PositiveInfinity 或 Double.NegativeInfinity。 但是,有一小组值被认为更接近 Double 的最大值或最小值,而不是正或负无穷大。 在这些情况下,该方法返回 Double.MaxValue 或 Double.MinValue。
如果在分析操作期间 s 参数中遇到分隔符,并且适用的货币或数字小数和组分隔符相同,则分析操作假定分隔符是小数分隔符,而不是组分隔符。 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparator、NumberDecimalSeparator、CurrencyGroupSeparator和 NumberGroupSeparator。
另请参阅
- ToString()
- 分析 .NET 中的数值字符串