Double.TryParse 方法

定義

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

多載

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span containing the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, Double)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Char>, Double)

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等的雙精確度浮點數。Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, NumberStyles, IFormatProvider, Double)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span containing the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out double result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * double -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Double) As Boolean

參數

s
ReadOnlySpan<Char>

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

style
NumberStyles

NumberStyles 值的位元組合,表示 s 的允許格式。A bitwise combination of NumberStyles values that indicates the permitted format of 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.

result
Double

當這個方法傳回時,若轉換成功,將會包含相當於 s 所含數值或符號的雙精確度浮點數。When this method returns and if the conversion succeeded, contains a double-precision floating-point number equivalent of the numeric value or symbol contained in s. 若轉換失敗,則會包含零。Contains zero if the conversion failed. 如果 s 參數為 null 或空字元範圍,或者其數字格式不符合 style 規範,則轉換會失敗。The conversion fails if the s parameter is null, an empty character span, or not a number in a format compliant with style. 如果 s 是小於 MinValue 的有效數字,resultNegativeInfinityIf s is a valid number less than MinValue, result is NegativeInfinity. 如果 s 是大於 MaxValue 的有效數字,則 resultPositiveInfinityIf s is a valid number greater than MaxValue, result is PositiveInfinity. 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

TryParse(String, Double)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (string s, out double result);
static member TryParse : string * double -> bool
Public Shared Function TryParse (s As String, ByRef result As Double) As Boolean

參數

s
String

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

result
Double

如果轉換成功,這個方法傳回時會包含相當於 s 參數的雙精確度浮點數,如果轉換失敗則為零。When this method returns, contains the double-precision floating-point number equivalent of the s parameter, if the conversion succeeded, or zero if the conversion failed. 如果 s 參數為 nullEmpty,或者不是有效格式的數字,則轉換會失敗。The conversion fails if the s parameter is null or Empty or is not a number in a valid format. 如果 s 代表小於 MinValue 或大於 MaxValue 的數字,在 .NET Framework 與 .NET Core 2.2 和更早版本上的轉換也會失敗。It also fails on .NET Framework and .NET Core 2.2 and earlier versions if s represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

範例

下列範例會使用 TryParse(String, Double) 方法,將數值的字串表示轉換成 Double 值。The following example uses the TryParse(String, Double) method to convert the string representations of numeric values to Double values. 它假設 en-us 是目前的文化特性。It assumes that en-US is the current culture.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "1,643.57", "$1,643.57", "-1.643e6", 
                          "-168934617882109132", "123AE6", 
                          null, String.Empty, "ABCDEF" };
      double number;
      
      foreach (var value in values) {
         if (Double.TryParse(value, out number)) 
            Console.WriteLine("'{0}' --> {1}", value, number);
         else
            Console.WriteLine("Unable to parse '{0}'.", value);      
      }   
   }
}
// The example displays the following output:
//       '1,643.57' --> 1643.57
//       Unable to parse '$1,643.57'.
//       '-1.643e6' --> -1643000
//       '-168934617882109132' --> -1.68934617882109E+17
//       Unable to parse '123AE6'.
//       Unable to parse ''.
//       Unable to parse ''.
//       Unable to parse 'ABCDEF'.
Module Example
   Public Sub Main()
      Dim values() As String = { "1,643.57", "$1,643.57", "-1.643e6", 
                                "-168934617882109132", "123AE6", 
                                Nothing, String.Empty, "ABCDEF" }
      Dim number As Double
      
      For Each value In values
         If Double.TryParse(value, number) Then
            Console.WriteLine("'{0}' --> {1}", value, number)
         Else
            Console.WriteLine("Unable to parse '{0}'.", value)      
         End If   
      Next   
   End Sub
End Module
' The example displays the following output:
'       '1,643.57' --> 1643.57
'       Unable to parse '$1,643.57'.
'       '-1.643e6' --> -1643000
'       '-168934617882109132' --> -1.68934617882109E+17
'       Unable to parse '123AE6'.
'       Unable to parse ''.
'       Unable to parse ''.
'       Unable to parse 'ABCDEF'.

備註

這個多載與 Double.Parse(String) 方法不同,藉由傳回布林值,指出剖析作業是否成功,而不是傳回剖析的數值。This overload differs from the Double.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. 如果 s 無效,而且無法成功剖析,就不需要使用例外狀況處理來測試 FormatExceptionIt eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

s 參數可以包含目前文化特性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol (字串比較會區分大小寫),或格式為的字串:The s parameter can contain the current culture's NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbol (the string comparison is case-sensitive), or a string of the form:

atl-ws-01簽訂[整數位數,] 整數位數 [.]小數-數位] [e [sign] 指數-數位] [ws][ws][sign][integral-digits,]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws]

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

項目Element 說明Description
wsws 一系列的空白字元。A series of white-space characters.
簽署sign 負號或正號符號。A negative sign or positive sign symbol.
整數位數integral-digits 一系列的數位字元,範圍從0到9,指定數位的整數部分。A series of numeric characters ranging from 0 to 9 that specify the integral part of the number. 如果有小數數位,整數位數可能不存在。Integral-digits can be absent if there are fractional-digits.
, 文化特性特定的群組分隔符號符號。A culture-specific group separator symbol.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數數位fractional-digits 一系列範圍為0到9的數位字元,指定數位的小數部分。A series of numeric characters ranging from 0 to 9 that specify the fractional part of the number.
EE 大寫或小寫字元 ' e ',表示指數(科學)標記法。An uppercase or lowercase character 'e', that indicates exponential (scientific) notation.
指數-數位exponential-digits 指定指數的一連串數位字元,範圍介於0到9之間。A series of numeric characters ranging from 0 to 9 that specify an exponent.

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

s 參數會使用 NumberStyles.FloatNumberStyles.AllowThousands 旗標的組合來加以解讀。The s parameter is interpreted by using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. 這表示允許使用空白字元和千位分隔符號,但是貨幣符號則不是。This means that white space and thousands separators are allowed but currency symbols are not. 若要明確定義 s中可以存在的元素(例如貨幣符號、千位分隔符號和空白字元),請使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法多載。To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method overload.

s 參數會使用針對目前系統文化特性初始化之 NumberFormatInfo 物件中的格式設定資訊來進行剖析。The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 如需詳細資訊,請參閱NumberFormatInfo.CurrentInfoFor more information, see NumberFormatInfo.CurrentInfo. 若要使用某些其他指定文化特性的格式資訊來剖析字串,請使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法多載。To parse a string using the formatting information of some other specified culture, use the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method overload.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.TryParse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.TryParse 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.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      double number;
      
      value = Double.MinValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.", 
                           value);
      
      value = Double.MaxValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           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.            
Module Example
   Public Sub Main()
      Dim value As String
      Dim number As Double
      
      value = Double.MinValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
      
      value = Double.MaxValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
   End Sub
End Module
' 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.            

在 .NET Framework 和 .NET Core 2.2 和更早版本上,如果 s 超出 Double 資料類型的範圍,TryParse(String, Double) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the TryParse(String, Double) 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. 在大部分情況下,TryParse(String, Double) 方法會計算 Double.PositiveInfinityDouble.NegativeInfinity的結果。In most cases, the TryParse(String, Double) method calculates a result of 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.MinValue的結果。In those cases, the method calculates a result of Double.MaxValue or Double.MinValue.

如果在剖析作業期間于 s 參數中遇到分隔符號,而且小數點和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號。If a separator is encountered in the s parameter during a parse operation, and the 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.

另請參閱

TryParse(ReadOnlySpan<Char>, Double)

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等的雙精確度浮點數。Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (ReadOnlySpan<char> s, out double result);
static member TryParse : ReadOnlySpan<char> * double -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Double) As Boolean

參數

s
ReadOnlySpan<Char>

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

result
Double

當這個方法傳回時,若轉換成功,將會包含相當於 s 參數所含數值或符號的雙精確度浮點數;若轉換失敗,則為零。When this method returns, contains the double-precision floating-point number equivalent of the numeric value or symbol contained in s parameter, if the conversion succeeded, or zero if the conversion failed. 如果 s 參數為 null 或空白,或者格式不符合 style 規範,則轉換會失敗。The conversion fails if the s parameter is null or empty, or is not in a format compliant with style. 如果 style 不是 NumberStyles 列舉常數的有效組合,轉換也會失敗。The conversion also fails if style is not a valid combination of NumberStyles enumerated constants. 如果 s 是小於 MinValue 的有效數字,resultNegativeInfinityIf s is a valid number less than MinValue, result is NegativeInfinity. 如果 s 是大於 MaxValue 的有效數字,則 resultPositiveInfinityIf s is a valid number greater than MaxValue, result is PositiveInfinity. 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

TryParse(String, NumberStyles, IFormatProvider, Double)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] double % result);
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out double result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * double -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Double) As Boolean

參數

s
String

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

style
NumberStyles

NumberStyles 值的位元組合,表示 s 的允許格式。A bitwise combination of NumberStyles values that indicates the permitted format of s. 要指定的一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

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

result
Double

當此方法傳回時,若轉換成功,包含相當於 s 中包含之數值或符號的雙精確度浮點數;若轉換失敗,則為零。When this method returns, contains a double-precision floating-point number equivalent of the numeric value or symbol contained in s, if the conversion succeeded, or zero if the conversion failed. 如果 s 參數是 nullEmpty、不是符合 style 規範的格式,或者 style 不是 NumberStyles 列舉常數的有效組合,則轉換會失敗。The conversion fails if the s parameter is null or Empty or is not in a format compliant with style, or if style is not a valid combination of NumberStyles enumeration constants. 如果 s 代表小於 MinValue 或大於 MaxValue 的數字,在 .NET Framework 或 .NET Core 2.2 和更早版本上的轉換也會失敗。It also fails on .NET Framework or .NET Core 2.2 and earlier versions if s represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都將遭到覆寫。This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

傳回

如果 true 轉換成功,則為 s,否則為 falsetrue if s was converted successfully; otherwise, false.

例外狀況

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

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

範例

下列範例示範如何使用 Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法來剖析具有特定樣式之數位的字串表示,並使用特定文化特性的慣例來格式化。The following example demonstrates the use of the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method to parse the string representation of numbers that have a particular style and are formatted using the conventions of a particular culture.

string value;
NumberStyles style;
CultureInfo culture;
double number;

// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays: 
//       Converted '£1,097.63' to 1097.63.

value = "1345,978";
style = NumberStyles.AllowDecimalPoint;
culture = CultureInfo.CreateSpecificCulture("fr-FR");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Converted '1345,978' to 1345.978.

value = "1.345,978";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
culture = CultureInfo.CreateSpecificCulture("es-ES");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays: 
//       Converted '1.345,978' to 1345.978.

value = "1 345,978";
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Unable to convert '1 345,978'.
Dim value As String
Dim style As NumberStyles
Dim culture As CultureInfo
Dim number As Double

' Parse currency value using en-GB culture.
value = "£1,097.63"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
culture = CultureInfo.CreateSpecificCulture("en-GB")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays: 
'       Converted '£1,097.63' to 1097.63.

value = "1345,978"
style = NumberStyles.AllowDecimalPoint
culture = CultureInfo.CreateSpecificCulture("fr-FR")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays:
'       Converted '1345,978' to 1345.978.

value = "1.345,978"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
culture = CultureInfo.CreateSpecificCulture("es-ES")
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays: 
'       Converted '1.345,978' to 1345.978.

value = "1 345,978"
If Double.TryParse(value, style, culture, number) Then
   Console.WriteLine("Converted '{0}' to {1}.", value, number)
Else
   Console.WriteLine("Unable to convert '{0}'.", value)
End If    
' Displays:
'       Unable to convert '1 345,978'.

備註

TryParse 方法與 Parse(String, NumberStyles, IFormatProvider) 方法類似,但此方法不會在轉換失敗時擲回例外狀況。The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. 如果轉換成功,則傳回值會 true,且 result 參數會設定為轉換的結果。If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. 如果轉換失敗,則傳回值為 false,且 result 參數設定為零。If the conversion fails, the return value is false and the result parameter is set to zero. 這樣就不需要在 s 無效且無法成功剖析的事件中,使用例外狀況處理來測試 FormatExceptionThis eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

style 參數會定義可讓剖析作業成功的 s 參數所允許的格式。The style parameter defines the allowable format of 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 indicated by provider. 此外,根據 style的值,s 參數可能包含下列元素:In addition, depending on the value of style, the s parameter may include the following elements:

atl-ws-01[$]簽訂[整數位數,] 整數位數 [. 小數數位] [e [正負號] 指數數位] [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 選擇性的空白字元。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,則會在 s 開頭顯示空白字元。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. 如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,它可以出現在 s 的結尾。It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是由 provider 參數的 IFormatProvider.GetFormat 方法所傳回 NumberFormatInfo 物件的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,貨幣符號可能會出現在 s 中。The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. 如果 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. 如果有小數數位,整數位數可能不存在。Integral-digits can be absent if there are fractional-digits.
, 文化特性特定的千位分隔符號。A culture-specific thousands separator symbol. 如果 style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的千位分隔符號可能會出現在 s 中。The current culture's thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 文化特性特定的小數點符號。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 表示 s 可以使用指數標記法來表示數位的 e 或 E 字元。The e or E character, which indicates that s can represent a number using exponential 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 members 控制項可能是但不需要出現在輸入字串中的元素。The remaining System.Globalization.NumberStyles members control elements that may be 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 . 小數數位的元素。and fractional-digits elements.
AllowExponent s 參數也可以使用指數標記法。The s parameter can also use exponential notation. 這個旗標本身可支援以整數位數E指數數位為格式的值;需要其他旗標,才能成功地以指數標記法來剖析字串,並將這類元素當做正或負號和小數點符號。This flag by itself supports values in the form integral-digitsEexponential-digits; additional flags are needed to successfully parse strings in exponential notation 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 , element.
AllowCurrencySymbol $ 元素。The $ element.
Currency 全部。All. s 參數不能以指數標記法表示十六進位數位或數位。The s parameter 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 . 百分號.symbol. s 參數也可以使用指數標記法。The s parameter can also use exponential notation.
Number wssign、千位分隔符號(、) 和小數點(.)元素。The ws, sign, thousands separator (,), and decimal point (.) elements.
Any 除了 s 以外的所有樣式都不能代表十六進位數位。All styles, except s cannot represent a hexadecimal number.

provider 參數是 IFormatProvider 的執行,例如 NumberFormatInfoCultureInfo 物件。The provider parameter is a IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. provider 參數提供用於剖析的特定文化特性資訊。The provider parameter supplies culture-specific information used in parsing. 如果 provider null 或無法取得 NumberFormatInfo 物件,則會使用目前文化特性的格式資訊。If provider is null or a NumberFormatInfo object cannot be obtained, the format information for the current culture is used.

如果 s 參數 null 或不是數值,provider 參數不會產生 NumberFormatInfo 物件,或 style 參數不是來自 NumberStyles 列舉的位旗標的組合,則轉換會失敗。The conversion fails if the s parameter is null or not a numeric value, the provider parameter does not yield a NumberFormatInfo object, or the style parameter is not a combination of bit flags from the NumberStyles enumeration.

一般來說,如果您將呼叫 Double.ToString 方法所建立的字串傳遞給 Double.TryParse 方法,則會傳回原始的 Double 值。Ordinarily, if you pass the Double.TryParse 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.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      double number;
      
      value = Double.MinValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.", 
                           value);
      
      value = Double.MaxValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           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.            
Module Example
   Public Sub Main()
      Dim value As String
      Dim number As Double
      
      value = Double.MinValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
      
      value = Double.MaxValue.ToString()
      If Double.TryParse(value, number) Then
         Console.WriteLine(number)
      Else
         Console.WriteLine("{0} is outside the range of a Double.", _
                           value)
      End If
   End Sub
End Module
' 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.            

在 .NET Framework 和 .NET Core 2.2 和更早版本上,如果 s 超出 Double 資料類型的範圍,Double.TryParse(String, NumberStyles, IFormatProvider, Double) 方法會擲回 OverflowExceptionOn .NET Framework and .NET Core 2.2 and earlier versions, if s is out of range of the Double data type, the Double.TryParse(String, NumberStyles, IFormatProvider, Double) 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.TryParse(String, NumberStyles, IFormatProvider, Double) 方法會計算 Double.PositiveInfinityDouble.NegativeInfinity的結果。In most cases, the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method calculates a result of 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.MinValue的結果。In those cases, the method calculates a result of 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.

另請參閱

適用於