Double.Parse 方法

定義

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent.

多載

Parse(String, NumberStyles, IFormatProvider)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Parse(String)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent.

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.

Parse(String, NumberStyles, IFormatProvider)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

public:
 static double Parse(System::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

字串,包含要轉換的數字。A string that contains a number to convert.

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicate the style elements that can be present in s. 要指定的一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

雙精確度浮點數,與 s 中指定的數值或符號相等。A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不代表數字。s does not represent a numeric value.

style 不是 NumberStyles 值。style is not a NumberStyles value.

-或--or- styleAllowHexSpecifier 值。style is the AllowHexSpecifier value.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

範例

下列範例說明如何使用 Parse(String, NumberStyles, IFormatProvider) 方法,將數個字串表示的溫度值指派給 Temperature 物件。The following example illustrates the use of the Parse(String, NumberStyles, IFormatProvider) method to assign several string representations of temperature values to a Temperature object.

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 Celcius) 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"));
   }
}
Imports System.Globalization

Public Class Temperature
   ' Parses the temperature from a string. Temperature scale is 
   ' indicated by 'F (for Fahrenheit) or 'C (for Celcius) 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   

備註

style 參數會定義可在 s 參數中允許的樣式元素(例如空白字元、千位分隔符號和貨幣符號),使剖析作業成功。The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. 它必須是來自 NumberStyles 列舉的位旗標組合。It must be a combination of bit flags from the NumberStyles enumeration. 不支援下列 NumberStyles 成員:The following NumberStyles members are not supported:

s 參數可以包含 provider所指定之文化特性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbolThe s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider. style的值而定,它也可以採用下列格式:Depending on the value of style, it can also take the form:

[ws][$][sign][整數位數,]整數位數[. [小數-數位]][E [sign]指數-數位][ws][ws] [$] [sign][integral-digits,]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

以方括弧([和])括住的元素是選擇性的。Elements framed in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 一系列的空白字元。A series of white-space characters. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,則空格可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,它可以出現在 s 的結尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是由目前文化特性的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可能會出現在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 負號符號(-)或正號符號(+)。A negative sign symbol (-) or a positive sign symbol (+). 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以出現在 s 的結尾。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 s 中使用括弧來表示負數值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
整數位數integral-digits 範圍從0到9的一系列數位,指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 如果字串包含小數位數元素,整數位數專案可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
,, 文化特性特定的群組分隔符號。A culture-specific group separator. 如果 style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符號符號可能會出現在 sThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
執行個體時提供 SQL Server 登入。. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前文化特性的小數點符號可能會出現在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
小數數位fractional-digits 一系列範圍為0到9的數位,指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,小數數位就會出現在 s 中。Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
指數-數位exponential-digits 指定指數的一系列數位,範圍介於0到9之間。A series of digits ranging from 0 to 9 that specify an exponent.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

僅限數位的字串(對應至 NumberStyles.None 樣式)一律會在 Double 類型的範圍內成功剖析。A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Double type. 在輸入字串中,其餘 System.Globalization.NumberStyles 成員控制可能存在但不需要存在的元素。The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. 下表指出個別 NumberStyles 旗標如何影響 s中可能存在的元素。The following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles 值NumberStyles value 除了數位之外,s 中允許的元素Elements permitted in s in addition to digits
None 僅限整數位數元素。The integral-digits element only.
AllowDecimalPoint 小數點(.)和小數位數元素。The decimal point (.) and fractional-digits elements.
AllowExponent "E" 或 "E" 字元,表示指數標記法。The "e" or "E" character, which indicates exponential notation. 這個旗標本身支援以數位**E 數位表示的值;需要有其他旗標,才能成功地將具有這類元素的字串剖析為正或負號和小數點符號。This flag by itself supports values in the form digitsEdigits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite s開頭的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s結尾的ws元素。The ws element at the end of s.
AllowLeadingSign s開頭的sign元素。The sign element at the beginning of s.
AllowTrailingSign s結尾的sign元素。The sign element at the end of s.
AllowParentheses 以括弧形式括住數值的sign元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符號(,)元素。The thousands separator (,) element.
AllowCurrencySymbol Currency ($)元素。The currency ($) element.
Currency 所有元素。All elements. 不過,s 不能以指數標記法來表示十六進位數位或數位。However, s cannot represent a hexadecimal number or a number in exponential notation.
Float s開頭或結尾的ws元素、s開頭的符號,以及小數點(.)符號。The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. s 參數也可以使用指數標記法。The s parameter can also use exponential notation.
Number wssign、千位分隔符號(、)和小數點(.)元素。The ws, sign, thousands separator (,) and decimal point (.) elements.
Any 所有元素。All elements. 不過,s 不能代表十六進位數位。However, s cannot represent a hexadecimal number.

provider 參數是 IFormatProvider 的實作為,其 GetFormat 方法會傳回 NumberFormatInfo 物件,以提供用來解讀 s格式的特定文化特性資訊。The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that supplies culture-specific information used in interpreting the format of s. 通常是 NumberFormatInfoCultureInfo 物件。Typically, it is a NumberFormatInfo or CultureInfo object. 如果 provider null 或無法取得 NumberFormatInfo,則會使用目前系統文化特性的格式資訊。If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.Parse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.Parse method a string that is created by calling the Double.ToString method, the original Double value is returned. 不過,由於遺失精確度,值可能不相等。However, because of a loss of precision, the values may not be equal. 此外,嘗試剖析 MinValueDouble.MaxValue 的字串表示時,將無法來回。In addition, attempting to parse the string representation of either MinValue or Double.MaxValue fails to round-trip. 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. 在 .NET Core 3.0 和更新版本中,如果您嘗試剖析 MaxValue,它會傳回 Double.PositiveInfinity MinValue Double.NegativeInfinityOn .NET Core 3.0 and later versions, it returns Double.NegativeInfinity if you attempt to parse MinValue or Double.PositiveInfinity if you attempt to parse MaxValue. 下列範例提供一個實例。The following example provides an illustration.

   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   
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) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Parse(String, NumberStyles, IFormatProvider) method throws an OverflowException.

在 .NET Core 3.0 和更新版本上,當 s 超出 Double 資料類型的範圍時,不會擲回例外狀況。On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. 在大部分情況下,Parse(String, NumberStyles, IFormatProvider) 方法會傳回 Double.PositiveInfinityDouble.NegativeInfinityIn most cases, the Parse(String, NumberStyles, IFormatProvider) method will return Double.PositiveInfinity or Double.NegativeInfinity. 不過,有一組較小的值會被視為接近 Double 的最大值或最小值,而不是正數或負無限大。However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. 在這些情況下,方法會傳回 Double.MaxValueDouble.MinValueIn those cases, the method returns Double.MaxValue or Double.MinValue.

如果在剖析作業期間于 s 參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號。If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.

public:
 static double Parse(System::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

字串,包含要轉換的數字。A string that contains a number to convert.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

雙精確度浮點數,與 s 中指定的數值或符號相等。A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是格式有效的數字。s does not represent a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

範例

下列範例是 Web 表單的按鈕 click 事件處理常式。The following example is the button click event handler of a Web form. 它會使用 HttpRequest.UserLanguages 屬性所傳回的陣列來判斷使用者的地區設定。It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. 接著,它會具現化對應至該地區設定的 CultureInfo 物件。It then instantiates a CultureInfo object that corresponds to that locale. 屬於該 CultureInfo 物件的 NumberFormatInfo 物件接著會傳遞至 Parse(String, IFormatProvider) 方法,以將使用者的輸入轉換成 Double 值。The NumberFormatInfo object that belongs to that CultureInfo object is then passed to the Parse(String, IFormatProvider) method to convert the user's input to a Double value.

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

備註

Parse(String, IFormatProvider) 方法的這個多載通常用來將可以多種方式格式化的文字轉換成 Double 值。This overload of the Parse(String, IFormatProvider) method is typically used to convert text that can be formatted in a variety of ways to a Double value. 例如,它可以用來將使用者輸入的文字轉換成 HTML 文字方塊中的數位值。For example, it can be used to convert the text that is entered by a user into an HTML text box to a numeric value.

s 參數會使用 NumberStyles.FloatNumberStyles.AllowThousands 旗標的組合來加以解讀。The s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. s 參數可以包含 provider所指定文化特性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol,或者它可以包含下列格式的字串:The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider, or it can contain a string of the form:

[ws][sign]整數位數[[小數-數位]][E [sign]指數-數位][ws][ws][sign]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

選擇性元素會以方括弧([和])括住。Optional elements are framed in square brackets ([ and ]). 包含「數位」一詞的元素包含一連串的數位字元,範圍介於0到9之間。Elements that contain the term "digits" consist of a series of numeric characters ranging from 0 to 9.

項目Element 說明Description
wsws 一系列的空白字元。A series of white-space characters.
簽署sign 負號符號(-)或正號符號(+)。A negative sign symbol (-) or a positive sign symbol (+).
整數位數integral-digits 範圍從0到9的一系列數位,指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 整數位數的執行可以透過群組分隔符號號進行分割。Runs of integral-digits can be partitioned by a group-separator symbol. 例如,在某些文化特性中,逗號(,)會分隔千位的群組。For example, in some cultures a comma (,) separates groups of thousands. 如果字串包含小數位數元素,整數位數專案可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
執行個體時提供 SQL Server 登入。. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數數位fractional-digits 一系列範圍為0到9的數位,指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
指數-數位exponential-digits 指定指數的一系列數位,範圍介於0到9之間。A series of digits ranging from 0 to 9 that specify an exponent.

如需數值格式的詳細資訊,請參閱格式化類型主題。For more information about numeric formats, see the Formatting Types topic.

provider 參數是 IFormatProvider 的實作為,其 GetFormat 方法會傳回 NumberFormatInfo 物件,以提供用來解讀 s格式的特定文化特性資訊。The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that supplies culture-specific information used in interpreting the format of s. 通常是 NumberFormatInfoCultureInfo 物件。Typically, it is a NumberFormatInfo or CultureInfo object. 如果 provider null 或無法取得 NumberFormatInfo,則會使用目前系統文化特性的格式資訊。If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.Parse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.Parse method a string that is created by calling the Double.ToString method, the original Double value is returned. 不過,由於遺失精確度,值可能不相等。However, because of a loss of precision, the values may not be equal. 此外,嘗試剖析 Double.MinValueDouble.MaxValue 的字串表示時,將無法來回。In addition, attempting to parse the string representation of either Double.MinValue or Double.MaxValue fails to round-trip. 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. 在 .NET Core 3.0 和更新版本中,如果您嘗試剖析 MaxValue,它會傳回 Double.PositiveInfinity MinValue Double.NegativeInfinityOn .NET Core 3.0 and later versions, it returns Double.NegativeInfinity if you attempt to parse MinValue or Double.PositiveInfinity if you attempt to parse MaxValue. 下列範例提供一個實例。The following example provides an illustration.

   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   
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) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Parse(String, IFormatProvider) method throws an OverflowException.

在 .NET Core 3.0 和更新版本上,當 s 超出 Double 資料類型的範圍時,不會擲回例外狀況。On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. 在大部分情況下,Parse(String, IFormatProvider) 方法會傳回 Double.PositiveInfinityDouble.NegativeInfinityIn most cases, the Parse(String, IFormatProvider) method will return Double.PositiveInfinity or Double.NegativeInfinity. 不過,有一組較小的值會被視為接近 Double 的最大值或最小值,而不是正數或負無限大。However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. 在這些情況下,方法會傳回 Double.MaxValueDouble.MinValueIn those cases, the method returns Double.MaxValue or Double.MinValue.

如果在剖析作業期間于 s 參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號。If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

public static double Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowTrailingWhite | System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.Integer, IFormatProvider provider = null);
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.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowTrailingWhite | System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = null) As Double

參數

s
ReadOnlySpan<Char>

字元範圍,其包含要轉換的數字。A character span that contains the number to convert.

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicate the style elements that can be present in s. 要指定的一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

雙精確度浮點數,與 s 中指定的數值或符號相等。A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

s 不代表數字。s does not represent a numeric value.

style 不是 NumberStyles 值。style is not a NumberStyles value.

-或--or- styleAllowHexSpecifier 值。style is the AllowHexSpecifier value.

備註

如果 s 超出 Double 資料類型的範圍,當 s 小於 Double.MinValue 時,此方法會傳回 Double.NegativeInfinity,如果 Double.PositiveInfinity 大於 s,則會傳回 Double.MaxValueIf s is out of range of the Double data type, the method returns Double.NegativeInfinity if s is less than Double.MinValue and Double.PositiveInfinity if s is greater than Double.MaxValue.

Parse(String)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent.

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

字串,包含要轉換的數字。A string that contains a number to convert.

傳回

雙精確度浮點數,與 s 中指定的數值或符號相等。A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是格式有效的數字。s does not represent a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

範例

在下列程式碼中,說明了如何使用 Parse(String) 方法。The following example illustrates the use of the Parse(String) method.

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;
        }
    }
}
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

備註

s 參數可以包含目前文化特性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol或格式的字串:The s parameter can contain the current culture's NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbol, or a string of the form:

[ws][sign][整數位數[]]整數位數[[小數-數位]][E [sign]指數-數位][ws][ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 一系列的空白字元。A series of white-space characters.
簽署sign 負號符號(-)或正號符號(+)。A negative sign symbol (-) or a positive sign symbol (+). 只能使用前置正負號。Only a leading sign can be used.
整數位數integral-digits 範圍從0到9的一系列數位,指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 整數位數的執行可以透過群組分隔符號號進行分割。Runs of integral-digits can be partitioned by a group-separator symbol. 例如,在某些文化特性中,逗號(,)會分隔千位的群組。For example, in some cultures a comma (,) separates groups of thousands. 如果字串包含小數位數元素,整數位數專案可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
,, 文化特性特定的千位分隔符號。A culture-specific thousands separator symbol.
執行個體時提供 SQL Server 登入。. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數數位fractional-digits 一系列範圍為0到9的數位,指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
指數-數位exponential-digits 指定指數的一系列數位,範圍介於0到9之間。A series of digits ranging from 0 to 9 that specify an exponent.

s 參數會使用 NumberStyles.FloatNumberStyles.AllowThousands 旗標的組合來加以解讀。The s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. 這表示允許空白字元和千位分隔符號,而貨幣符號則否。This means that white space and thousands separators are allowed, for example, while currency symbols are not. 若要更精確地控制 s 中允許剖析作業成功的樣式元素,請呼叫 Double.Parse(String, NumberStyles)Double.Parse(String, NumberStyles, IFormatProvider) 方法。For finer control over which style elements are permitted in s for the parse operation to succeed, call the Double.Parse(String, NumberStyles) or the Double.Parse(String, NumberStyles, IFormatProvider) method.

s 參數會使用針對目前線程文化特性初始化的 NumberFormatInfo 物件中的格式設定資訊來加以解讀。The s parameter is interpreted using the formatting information in a NumberFormatInfo object that is initialized for the current thread culture. 如需詳細資訊,請參閱CurrentInfoFor more information, see CurrentInfo. 若要使用一些其他文化特性的格式資訊來剖析字串,請呼叫 Double.Parse(String, IFormatProvider)Double.Parse(String, NumberStyles, IFormatProvider) 方法。To parse a string using the formatting information of some other culture, call the Double.Parse(String, IFormatProvider) or Double.Parse(String, NumberStyles, IFormatProvider) method.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.Parse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.Parse method a string that is created by calling the Double.ToString method, the original Double value is returned. 不過,在 .NET Framework 和 .NET Core 2.2 和更早版本上,這些值可能會因為遺失精確度而不相等。However, on .NET Framework and on .NET Core 2.2 and earlier versions, the values may not be equal because of a loss of precision. 此外,嘗試剖析 Double.MinValueDouble.MaxValue 的字串表示時,將無法來回。In addition, attempting to parse the string representation of either Double.MinValue or Double.MaxValue fails to round-trip. 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. 下列範例提供一個實例。The following example provides an illustration.

   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   
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) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Parse(String) method throws an OverflowException.

在 .NET Core 3.0 和更新版本上,當 s 超出 Double 資料類型的範圍時,不會擲回例外狀況。On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. 在大部分情況下,方法會傳回 Double.PositiveInfinityDouble.NegativeInfinityIn most cases, the method will return Double.PositiveInfinity or Double.NegativeInfinity. 不過,有一組較小的值會被視為接近 Double 的最大值或最小值,而不是正數或負無限大。However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. 在這些情況下,方法會傳回 Double.MaxValueDouble.MinValueIn those cases, the method returns Double.MaxValue or Double.MinValue.

如果在剖析作業期間于 s 參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號。If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.

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

字串,包含要轉換的數字。A string that contains a number to convert.

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicate the style elements that can be present in s. 要指定的一般值為 FloatAllowThousands 的組合。A typical value to specify is a combination of Float combined with AllowThousands.

傳回

雙精確度浮點數,與 s 中指定的數值或符號相等。A double-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是格式有效的數字。s does not represent a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

style 不是 NumberStyles 值。style is not a NumberStyles value.

-或--or- style 包含 AllowHexSpecifier 值。style includes the AllowHexSpecifier value.

範例

下列範例會使用 Parse(String, NumberStyles) 方法,利用 en-us 文化特性來剖析 Double 值的字串表示。The following example uses the Parse(String, NumberStyles) method to parse the string representations of Double values using the en-US culture.

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.   
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.   

備註

style 參數會定義可在 s 參數中允許的樣式元素(例如空白字元、千位分隔符號和貨幣符號),使剖析作業成功。The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. 它必須是來自 NumberStyles 列舉的位旗標組合。It must be a combination of bit flags from the NumberStyles enumeration. 不支援下列 NumberStyles 成員:The following NumberStyles members are not supported:

s 參數可以包含目前文化特性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbolThe s parameter can contain the current culture's NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol. style的值而定,它也可以採用下列格式:Depending on the value of style, it can also take the form:

[ws][$][sign][整數位數[]]整數位數[[小數-數位]][E [sign]指數-數位][ws][ws][$][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 說明Description
wsws 一系列的空白字元。A series of white-space characters. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,則空格可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,它可以出現在 s 的結尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是由目前文化特性的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可能會出現在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 負號符號(-)或正號符號(+)。A negative sign symbol (-) or a positive sign symbol (+). 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 s 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以出現在 s 的結尾。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 s 中使用括弧來表示負數值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
整數位數integral-digits 範圍從0到9的一系列數位,指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 如果字串包含小數位數元素,整數位數專案可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
,, 文化特性特定的群組分隔符號。A culture-specific group separator. 如果 style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符號符號可能會出現在 sThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
執行個體時提供 SQL Server 登入。. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前文化特性的小數點符號可能會出現在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
小數數位fractional-digits 一系列範圍為0到9的數位,指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,小數數位就會出現在 s 中。Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. 如果 style 包含 NumberStyles.AllowExponent 旗標,s 參數可以表示指數標記法中的數位。The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
指數-數位exponential-digits 指定指數的一系列數位,範圍介於0到9之間。A series of digits ranging from 0 to 9 that specify an exponent.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

僅限數位的字串(對應至 NumberStyles.None 樣式)一律會在 Double 類型的範圍內成功剖析。A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Double type. 在輸入字串中,其餘 System.Globalization.NumberStyles 成員控制可能存在但不需要存在的元素。The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. 下表指出個別 NumberStyles 旗標如何影響 s中可能存在的元素。The following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles 值NumberStyles value 除了數位之外,s 中允許的元素Elements permitted in s in addition to digits
None 僅限整數位數元素。The integral-digits element only.
AllowDecimalPoint 小數點(.)和小數位數元素。The decimal point (.) and fractional-digits elements.
AllowExponent "E" 或 "E" 字元,表示指數標記法。The "e" or "E" character, which indicates exponential notation. 這個旗標本身支援以數位**E 數位表示的值;需要有其他旗標,才能成功地將具有這類元素的字串剖析為正或負號和小數點符號。This flag by itself supports values in the form digitsEdigits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite s開頭的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s結尾的ws元素。The ws element at the end of s.
AllowLeadingSign s開頭的sign元素。The sign element at the beginning of s.
AllowTrailingSign s結尾的sign元素。The sign element at the end of s.
AllowParentheses 以括弧形式括住數值的sign元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符號(,)元素。The thousands separator (,) element.
AllowCurrencySymbol Currency ($)元素。The currency ($) element.
Currency 所有元素。All elements. 不過,s 不能以指數標記法來表示十六進位數位或數位。However, s cannot represent a hexadecimal number or a number in exponential notation.
Float s開頭或結尾的ws元素、s開頭的符號,以及小數點(.)符號。The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. s 參數也可以使用指數標記法。The s parameter can also use exponential notation.
Number wssign、千位分隔符號(、)和小數點(.)元素。The ws, sign, thousands separator (,) and decimal point (.) elements.
Any 所有元素。All elements. 不過,s 不能代表十六進位數位。However, s cannot represent a hexadecimal number.

s 參數會使用針對目前系統文化特性初始化之 NumberFormatInfo 物件中的格式設定資訊來進行剖析。The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 如需詳細資訊,請參閱CurrentInfoFor more information, see CurrentInfo.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.Parse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.Parse method a string that is created by calling the Double.ToString method, the original Double value is returned. 不過,由於遺失精確度,值可能不相等。However, because of a loss of precision, the values may not be equal. 此外,嘗試剖析 Double.MinValueDouble.MaxValue 的字串表示時,將無法來回。In addition, attempting to parse the string representation of either Double.MinValue or Double.MaxValue fails to round-trip. 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and previous versions, it throws an OverflowException. 在 .NET Core 3.0 和更新版本中,如果您嘗試剖析 MaxValue,它會傳回 Double.PositiveInfinity MinValue Double.NegativeInfinityOn .NET Core 3.0 and later versions, it returns Double.NegativeInfinity if you attempt to parse MinValue or Double.PositiveInfinity if you attempt to parse MaxValue. 下列範例提供一個實例。The following example provides an illustration.

   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   
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) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Parse(String, NumberStyles) method throws an OverflowException.

在 .NET Core 3.0 和更新版本上,當 s 超出 Double 資料類型的範圍時,不會擲回例外狀況。On .NET Core 3.0 and later versions, no exception is thrown when s is out of range of the Double data type. 在大部分情況下,Parse(String, NumberStyles) 方法會傳回 Double.PositiveInfinityDouble.NegativeInfinityIn most cases, the Parse(String, NumberStyles) method will return Double.PositiveInfinity or Double.NegativeInfinity. 不過,有一組較小的值會被視為接近 Double 的最大值或最小值,而不是正數或負無限大。However, there is a small set of values that are considered to be closer to the maximum or minimum values of Double than to positive or negative infinity. 在這些情況下,方法會傳回 Double.MaxValueDouble.MinValueIn those cases, the method returns Double.MaxValue or Double.MinValue.

如果在剖析作業期間于 s 參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號。If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於