Double.Parse Double.Parse Double.Parse Double.Parse Method

定義

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

多載

Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) 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) Parse(String, IFormatProvider) Parse(String, IFormatProvider) 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) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Parse(String) Parse(String) Parse(String) Parse(String)

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

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

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

style
NumberStyles NumberStyles NumberStyles 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 IFormatProvider IFormatProvider 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 代表小於 MinValue 或大於 MaxValue 的數字。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   

備註

參數會定義s參數中允許的樣式元素 (例如空白字元、千位分隔符號和貨幣符號), 使剖析作業成功。 styleThe 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:

NumberFormatInfo.PositiveInfinitySymbol provider參數可以包含、NumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol , 適用于所指定的文化特性。 sThe 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. s s style NumberStyles.AllowTrailingWhite如果包含style 旗標,空白字元可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingWhite出現在的結尾。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.CurrencyNegativePattern目前文化特性的和NumberFormatInfo.CurrencyPositivePattern屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果s style包含旗標,則目前文化特性的貨幣符號可能會出現在中。NumberStyles.AllowCurrencySymbolThe 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 (+). s s style NumberStyles.AllowTrailingSign如果包含style 旗標,則正負號可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingSign出現在的結尾。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. 如果包含s style 旗標,則可以在中使用括弧來NumberStyles.AllowParentheses表示負數值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digitsintegral-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. 如果s style包含旗標,則目前文化特性的群組分隔符號符號可能會出現在中NumberStyles.AllowThousandsThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果s style包含旗標,則目前文化特性的小數點符號可能會出現在中。NumberStyles.AllowDecimalPointThe current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsfractional-digits 一系列範圍為0到9的數位, 指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果s style包含旗標,可以在中顯示小數數位。NumberStyles.AllowDecimalPointFractional 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. 如果s 包含旗NumberStyles.AllowExponent標, 參數可以表示指數標記法中的數位。 styleThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digitsexponential-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樣式) 一律會成功剖析。A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. 在輸入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 開頭sws元素。The ws element at the beginning of s.
AllowTrailingWhite 結尾sws元素。The ws element at the end of s.
AllowLeadingSign 在開頭s的 sign 元素。The sign element at the beginning of s.
AllowTrailingSign 結尾ssign元素。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.

IFormatProvider 參數是GetFormat一個執行,s其方法會傳回物件,提供用來解讀之格式的特定文化特性資訊。NumberFormatInfo providerThe 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. 如果providernullNumberFormatInfo無法取得, 則會使用目前系統文化特性的格式資訊。If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

一般來說, 如果您將Double.Parse Double.ToString呼叫方法所建立的字串傳遞給方法, 則會傳回原始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. 此外, 嘗試剖析MinValueMaxValue OverflowException的字串表示會擲回, 如下列範例所示。In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

   string value;
   
   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }   
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
   
   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
// 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.
Dim value As String

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

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine("{0} is outside the range of the Double type.", _
                     value)
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.            

如果在剖析作業期間于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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

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

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

provider
IFormatProvider IFormatProvider IFormatProvider 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 number in a valid format.

s 代表小於 MinValue 或大於 MaxValue 的數字。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物件的Parse(String, IFormatProvider) Double物件會傳遞至方法, 以將使用者的輸入轉換成值。 NumberFormatInfoThe 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

備註

此方法的多載通常用來將可以各種方式Double格式化的文字轉換成值。 Parse(String, IFormatProvider)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.

參數是使用NumberStyles.FloatNumberStyles.AllowThousands旗標的組合來解讀。 sThe s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. NumberFormatInfo.PositiveInfinitySymbol參數可以NumberFormatInfo.NegativeInfinitySymbol包含或所NumberFormatInfo.NaNSymbol指定之provider文化特性的、或, 也可以包含下列格式的字串: sThe 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]integral-digits[.[fractional-digits]][E[sign]exponential-digits][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-digitsintegral-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 decimal point symbol.
fractional-digitsfractional-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-digitsexponential-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.

IFormatProvider 參數是GetFormat一個執行,s其方法會傳回物件,提供用來解讀之格式的特定文化特性資訊。NumberFormatInfo providerThe 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. 如果providernullNumberFormatInfo無法取得, 則會使用目前系統文化特性的格式資訊。If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

一般來說, 如果您將Double.Parse Double.ToString呼叫方法所建立的字串傳遞給方法, 則會傳回原始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. 此外, 嘗試剖析MinValueMaxValue OverflowException的字串表示會擲回, 如下列範例所示。In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

   string value;
   
   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }   
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
   
   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
// 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.
Dim value As String

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

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine("{0} is outside the range of the Double type.", _
                     value)
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.            

如果在剖析作業期間于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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

參數

傳回

Parse(String) Parse(String) Parse(String) 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 String String 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.

例外狀況

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

s 代表小於 MinValue 或大於 MaxValue 的數字。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

備註

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

[ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][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-digitsintegral-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.
. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
fractional-digitsfractional-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-digitsexponential-digits 指定指數的一系列數位, 範圍介於0到9之間。A series of digits ranging from 0 to 9 that specify an exponent.

參數是使用NumberStyles.FloatNumberStyles.AllowThousands旗標的組合來解讀。 sThe 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.

參數會使用針對目前線程文化特性初始化之NumberFormatInfo物件中的格式資訊來加以解讀。 sThe 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.Parse Double.ToString呼叫方法所建立的字串傳遞給方法, 則會傳回原始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. 此外, 嘗試剖析MinValueMaxValue OverflowException的字串表示會擲回, 如下列範例所示。In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

   string value;
   
   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }   
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
   
   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
// 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.
Dim value As String

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

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine("{0} is outside the range of the Double type.", _
                     value)
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.            

如果在剖析作業期間于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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

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

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

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

例外狀況

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

s 代表小於 MinValue 或大於 MaxValue 的數字。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.   

備註

參數會定義s參數中允許的樣式元素 (例如空白字元、千位分隔符號和貨幣符號), 使剖析作業成功。 styleThe 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:

參數可以包含目前文化特性的NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbolsThe 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. s s style NumberStyles.AllowTrailingWhite如果包含style 旗標,空白字元可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingWhite出現在的結尾。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.CurrencyNegativePattern目前文化特性的和NumberFormatInfo.CurrencyPositivePattern屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果s style包含旗標,則目前文化特性的貨幣符號可能會出現在中。NumberStyles.AllowCurrencySymbolThe 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 (+). s s style NumberStyles.AllowTrailingSign如果包含style 旗標,則正負號可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingSign出現在的結尾。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. 如果包含s style 旗標,則可以在中使用括弧來NumberStyles.AllowParentheses表示負數值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digitsintegral-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. 如果s style包含旗標,則目前文化特性的群組分隔符號符號可能會出現在中NumberStyles.AllowThousandsThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果s style包含旗標,則目前文化特性的小數點符號可能會出現在中。NumberStyles.AllowDecimalPointThe current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsfractional-digits 一系列範圍為0到9的數位, 指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果s style包含旗標,可以在中顯示小數數位。NumberStyles.AllowDecimalPointFractional 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. 如果s 包含旗NumberStyles.AllowExponent標, 參數可以表示指數標記法中的數位。 styleThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digitsexponential-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樣式) 一律會成功剖析。A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. 在輸入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 開頭sws元素。The ws element at the beginning of s.
AllowTrailingWhite 結尾sws元素。The ws element at the end of s.
AllowLeadingSign 在開頭s的 sign 元素。The sign element at the beginning of s.
AllowTrailingSign 結尾ssign元素。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.

參數會使用針對目前系統文化特性初始化之NumberFormatInfo物件中的格式資訊來進行剖析。 sThe 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.Parse Double.ToString呼叫方法所建立的字串傳遞給方法, 則會傳回原始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. 此外, 嘗試剖析MinValueMaxValue OverflowException的字串表示會擲回, 如下列範例所示。In addition, attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the following example illustrates.

   string value;
   
   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }   
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
   
   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine("{0} is outside the range of the Double type.",
                        value);
   }
// 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.
Dim value As String

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

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine("{0} is outside the range of the Double type.", _
                     value)
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.            

如果在剖析作業期間于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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於