Double.Parse 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將數字的字串表示轉換為其相等的雙精確度浮點數。
多載
Parse(String) |
將數字的字串表示轉換為其相等的雙精確度浮點數。 |
Parse(ReadOnlySpan<Byte>, IFormatProvider) |
將UTF-8字元的範圍剖析為值。 |
Parse(ReadOnlySpan<Char>, IFormatProvider) |
將字元範圍剖析為值。 |
Parse(String, NumberStyles) |
將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。 |
Parse(String, IFormatProvider) |
將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。 |
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
將UTF-8字元的範圍剖析為值。 |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。 |
Parse(String, NumberStyles, IFormatProvider) |
使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。 |
備註
在 .NET Core 3.0 和更新版本中,無法表示的值會四捨五入或 PositiveInfinityNegativeInfinity IEEE 754 規格所需的值。 在舊版中,包括 .NET Framework,剖析太大而無法表示的值會導致失敗。
Parse(String)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
將數字的字串表示轉換為其相等的雙精確度浮點數。
public:
static double Parse(System::String ^ s);
public static double Parse (string s);
static member Parse : string -> double
Public Shared Function Parse (s As String) As Double
參數
- s
- String
字串,其包含要轉換的數字。
傳回
雙精確度浮點數,與 s
中指定的數值或符號相等。
例外狀況
s
為 null
。
s
不是有效格式的數字。
僅 .NET Framework 和 .NET Core 2.2 和舊版:s
代表小於 Double.MinValue 或大於 Double.MaxValue 的數位。
範例
在下列程式碼中,說明了如何使用 Parse(String) 方法。
public ref class Temperature
{
// Parses the temperature from a string in form
// [ws][sign]digits['F|'C][ws]
public:
static Temperature^ Parse( String^ s )
{
Temperature^ temp = gcnew Temperature;
if ( s->TrimEnd(nullptr)->EndsWith( "'F" ) )
{
temp->Value = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
}
else
if ( s->TrimEnd(nullptr)->EndsWith( "'C" ) )
{
temp->Celsius = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
}
else
{
temp->Value = Double::Parse( s );
}
return temp;
}
protected:
// The value holder
double m_value;
public:
property double Value
{
double get()
{
return m_value;
}
void set( double value )
{
m_value = value;
}
}
property double Celsius
{
double get()
{
return (m_value - 32.0) / 1.8;
}
void set( double value )
{
m_value = 1.8 * value + 32.0;
}
}
};
public class Temperature {
// Parses the temperature from a string in form
// [ws][sign]digits['F|'C][ws]
public static Temperature Parse(string s) {
Temperature temp = new Temperature();
if( s.TrimEnd(null).EndsWith("'F") ) {
temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
}
else if( s.TrimEnd(null).EndsWith("'C") ) {
temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
}
else {
temp.Value = Double.Parse(s);
}
return temp;
}
// The value holder
protected double m_value;
public double Value {
get {
return m_value;
}
set {
m_value = value;
}
}
public double Celsius {
get {
return (m_value-32.0)/1.8;
}
set {
m_value = 1.8*value+32.0;
}
}
}
type Temperature() =
// Parses the temperature from a string in form
// [ws][sign]digits['F|'C][ws]
static member Parse(s: string) =
let temp = Temperature()
if s.TrimEnd(null).EndsWith "'F" then
temp.Value <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
elif s.TrimEnd(null).EndsWith "'C" then
temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
else
temp.Value <- Double.Parse s
temp
member val Value = 0. with get, set
member this.Celsius
with get () =
(this.Value - 32.) / 1.8
and set (value) =
this.Value <- 1.8 * value + 32.
Public Class Temperature
' Parses the temperature from a string in form
' [ws][sign]digits['F|'C][ws]
Public Shared Function Parse(ByVal s As String) As Temperature
Dim temp As New Temperature()
If s.TrimEnd(Nothing).EndsWith("'F") Then
temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
Else
If s.TrimEnd(Nothing).EndsWith("'C") Then
temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
Else
temp.Value = Double.Parse(s)
End If
End If
Return temp
End Function 'Parse
' The value holder
Protected m_value As Double
Public Property Value() As Double
Get
Return m_value
End Get
Set(ByVal Value As Double)
m_value = Value
End Set
End Property
Public Property Celsius() As Double
Get
Return (m_value - 32) / 1.8
End Get
Set(ByVal Value As Double)
m_value = Value * 1.8 + 32
End Set
End Property
End Class
備註
在 .NET Core 3.0 和更新版本中,無法表示的值會四捨五入或 PositiveInfinityNegativeInfinity IEEE 754 規格所需的值。 在舊版中,包括 .NET Framework,剖析太大而無法表示的值會導致失敗。
參數 s
可以包含目前文化特性的 NumberFormatInfo.PositiveInfinitySymbol、 NumberFormatInfo.NegativeInfinitySymbol、 NumberFormatInfo.NaNSymbol或格式的字串:
[ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
在方括號 ([ 和 ]) 中的項目是選擇性的項目。 下表說明每個元素。
元素 | 描述 |
---|---|
ws | 一系列的空格符。 |
簽署 | 負號符號 ( ) 或正負號符號 (+) 。 只能使用前置符號。 |
integral-digits | 一連串的數位,範圍從 0 到 9,指定數位的整數部分。 整數位數的執行可由群組分隔符分割。 例如,在某些文化特性中,逗號 (,) 分隔數千個群組。 如果字串包含小數位數元素,整數位數元素就不存在。 |
, | 特定文化特性的千位分隔符符號。 |
. | 特定文化特性的小數點符號。 |
fractional-digits | 一連串的數位,範圍從 0 到 9,指定數位的小數部分。 |
E | “e” 或 “E” 字元,表示值是以指數 (科學) 表示法表示。 |
指數數位 | 指定指數的一系列數位範圍從 0 到 9。 |
參數s
是使用 和 NumberStyles.AllowThousands 旗標的組合NumberStyles.Float來解譯。 這表示允許空格符和千位分隔符,例如,貨幣符號則不允許。 若要更精細地控制中允許 s
哪些樣式專案讓剖析作業成功,請呼叫 Double.Parse(String, NumberStyles) 或 Double.Parse(String, NumberStyles, IFormatProvider) 方法。
參數 s
是使用對象中 NumberFormatInfo 針對目前文化特性初始化的格式資訊來解譯。 如需詳細資訊,請參閱CurrentInfo。 若要使用其他文化特性的格式資訊剖析字串,請呼叫 Double.Parse(String, IFormatProvider) 或 Double.Parse(String, NumberStyles, IFormatProvider) 方法。
一般而言,如果您傳遞 Double.Parse 方法所建立 Double.ToString 的字串,則會傳回原始 Double 值。 不過,在 .NET Framework 和 .NET Core 2.2 和舊版上,這些值可能會因為精確度遺失而不相等。 此外,嘗試剖析 或 Double.MaxValue 無法往返的字串表示Double.MinValue。 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowException。 下列範例提供說明。
string value;
value = Double.MinValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
value = Double.MaxValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// Format without the default precision.
value = Double.MinValue.ToString("G17");
try
{
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException)
{
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
open System
[<EntryPoint>]
let main _ =
let value = string Double.MinValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
let value = string Double.MaxValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
// Format without the default precision.
let value = Double.MinValue.ToString "G17"
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
0
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
Dim value As String
value = Double.MinValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
value = Double.MaxValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
' -1.79769313486232E+308 is outside the range of the Double type.
' 1.79769313486232E+308 is outside the range of the Double type.
' -1.79769313486232E+308
在 .NET Framework 和 .NET Core 2.2 和舊版上,如果s
數據類型超出範圍Double,則Parse(String)方法會OverflowException擲回 。
在 .NET Core 3.0 和更新版本上,當超出數據類型的範圍Double時s
,不會擲回例外狀況。 在大部分情況下,方法會傳回 Double.PositiveInfinity 或 Double.NegativeInfinity。 不過,有一組小的值會被視為比正或負無限大接近最大值或最小值 Double 。 在這些情況下,方法會傳 Double.MaxValue 回 或 Double.MinValue。
如果在剖析作業期間於 參數中 s
遇到分隔符,且適用的貨幣或數位十進位和群組分隔符相同,則剖析作業會假設分隔符是小數分隔符,而不是群組分隔符。 如需分隔符的詳細資訊,請參閱CurrencyDecimalSeparator、 NumberDecimalSeparatorCurrencyGroupSeparator、 和 NumberGroupSeparator。
另請參閱
適用於
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
將UTF-8字元的範圍剖析為值。
public:
static double Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<double>::Parse;
public static double Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Double
參數
- utf8Text
- ReadOnlySpan<Byte>
要剖析的UTF-8字元範圍。
- provider
- IFormatProvider
提供關於 utf8Text
之特定文化特性格式資訊的物件。
傳回
剖析 utf8Text
的結果。
實作
適用於
Parse(ReadOnlySpan<Char>, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
將字元範圍剖析為值。
public:
static double Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<double>::Parse;
public static double Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Double
參數
- s
- ReadOnlySpan<Char>
要剖析的字元範圍。
- provider
- IFormatProvider
提供關於 s
之特定文化特性格式資訊的物件。
傳回
剖析 s
的結果。
實作
適用於
Parse(String, NumberStyles)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。
public:
static double Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static double Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> double
Public Shared Function Parse (s As String, style As NumberStyles) As Double
參數
- s
- String
字串,其包含要轉換的數字。
- style
- NumberStyles
列舉值的位元組合,其表示 s
中可以存在的樣式項目。 要指定的一般值為 Float 與 AllowThousands 的組合。
傳回
雙精確度浮點數,與 s
中指定的數值或符號相等。
例外狀況
s
為 null
。
s
不是有效格式的數字。
僅 .NET Framework 和 .NET Core 2.2 和舊版:s
代表小於 Double.MinValue 或大於 Double.MaxValue 的數位。
範例
下列範例會 Parse(String, NumberStyles) 使用 方法來剖析使用 en-US 文化特性的值字串表示 Double 。
public static void Main()
{
// Set current thread culture to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
string value;
NumberStyles styles;
// Parse a string in exponential notation with only the AllowExponent flag.
value = "-1.063E-02";
styles = NumberStyles.AllowExponent;
ShowNumericValue(value, styles);
// Parse a string in exponential notation
// with the AllowExponent and Number flags.
styles = NumberStyles.AllowExponent | NumberStyles.Number;
ShowNumericValue(value, styles);
// Parse a currency value with leading and trailing white space, and
// white space after the U.S. currency symbol.
value = " $ 6,164.3299 ";
styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
ShowNumericValue(value, styles);
// Parse negative value with thousands separator and decimal.
value = "(4,320.64)";
styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
NumberStyles.Float;
ShowNumericValue(value, styles);
styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
NumberStyles.Float | NumberStyles.AllowThousands;
ShowNumericValue(value, styles);
}
private static void ShowNumericValue(string value, NumberStyles styles)
{
double number;
try
{
number = Double.Parse(value, styles);
Console.WriteLine("Converted '{0}' using {1} to {2}.",
value, styles.ToString(), number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}' with styles {1}.",
value, styles.ToString());
}
Console.WriteLine();
}
// The example displays the following output to the console:
// Unable to parse '-1.063E-02' with styles AllowExponent.
//
// Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
// Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299.
//
// Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
open System
open System.Globalization
open System.Threading
let showNumericValue (value: string) (styles: NumberStyles) =
try
let number = Double.Parse(value, styles)
printfn $"Converted '{value}' using {styles} to {number}."
with :? FormatException ->
printfn $"Unable to parse '{value}' with styles {styles}."
printfn ""
[<EntryPoint>]
let main _ =
// Set current thread culture to en-US.
Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"
// Parse a string in exponential notation with only the AllowExponent flag.
let value = "-1.063E-02"
let styles = NumberStyles.AllowExponent
showNumericValue value styles
// Parse a string in exponential notation
// with the AllowExponent and Number flags.
let styles = NumberStyles.AllowExponent ||| NumberStyles.Number
showNumericValue value styles
// Parse a currency value with leading and trailing white space, and
// white space after the U.S. currency symbol.
let value = " $ 6,164.3299 "
let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
showNumericValue value styles
// Parse negative value with thousands separator and decimal.
let value = "(4,320.64)"
let styles =
NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float
showNumericValue value styles
let styles =
NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
showNumericValue value styles
0
// The example displays the following output to the console:
// Unable to parse '-1.063E-02' with styles AllowExponent.
//
// Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
// Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299.
//
// Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Public Sub Main()
' Set current thread culture to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
Dim value As String
Dim styles As NumberStyles
' Parse a string in exponential notation with only the AllowExponent flag.
value = "-1.063E-02"
styles = NumberStyles.AllowExponent
ShowNumericValue(value, styles)
' Parse a string in exponential notation
' with the AllowExponent and Number flags.
styles = NumberStyles.AllowExponent Or NumberStyles.Number
ShowNumericValue(value, styles)
' Parse a currency value with leading and trailing white space, and
' white space after the U.S. currency symbol.
value = " $ 6,164.3299 "
styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
ShowNumericValue(value, styles)
' Parse negative value with thousands separator and decimal.
value = "(4,320.64)"
styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
Or NumberStyles.Float
ShowNumericValue(value, styles)
styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
Or NumberStyles.Float Or NumberStyles.AllowThousands
ShowNumericValue(value, styles)
End Sub
Private Sub ShowNumericValue(value As String, styles As NumberStyles)
Dim number As Double
Try
number = Double.Parse(value, styles)
Console.WriteLine("Converted '{0}' using {1} to {2}.", _
value, styles.ToString(), number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
value, styles.ToString())
End Try
Console.WriteLine()
End Sub
' The example displays the following output to the console:
' Unable to parse '-1.063E-02' with styles AllowExponent.
'
' Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'
' Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299.
'
' Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'
' Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
備註
在 .NET Core 3.0 和更新版本中,無法表示的值會四捨五入或 PositiveInfinityNegativeInfinity IEEE 754 規格所需的值。 在舊版中,包括 .NET Framework,剖析太大而無法表示的值會導致失敗。
參數 style
會定義樣式專案 (,例如空格符、千位分隔符和貨幣符號,) 參數中 s
允許的樣式專案,讓剖析作業成功。 它必須是列舉中的 NumberStyles 位旗標組合。 不支援下列 NumberStyles 成員:
參數 s
可以包含目前文化特性的 NumberFormatInfo.PositiveInfinitySymbol、 NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol。 視 的值 style
而定,它也可以採用下列格式:
[ws][$][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
在方括號 ([ 和 ]) 中的項目是選擇性的項目。 下表說明每個元素。
元素 | 描述 |
---|---|
ws | 一系列的空格符。 如果style 包含 旗標,NumberStyles.AllowLeadingWhite則空格符可以出現在的s 開頭,如果style 包含 NumberStyles.AllowTrailingWhite 旗標,則會出現在 結尾s 。 |
$ | 特定文化特性的貨幣符號。 字串中的位置是由目前文化特性的 和 NumberFormatInfo.CurrencyPositivePattern 屬性所NumberFormatInfo.CurrencyNegativePattern定義。 如果style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可以出現在 s 中。 |
簽署 | 負號符號 ( ) 或正負號符號 (+) 。 如果 style 包含旗標,NumberStyles.AllowLeadingSign則符號可以出現在的s 開頭,如果style 包含 NumberStyles.AllowTrailingSign 旗標,則它可能會出現在 結尾s 。 如果style 包含 NumberStyles.AllowParentheses 旗標,可以使用 s 括號來表示負值。 |
integral-digits | 一連串的數位,範圍從 0 到 9,指定數位的整數部分。 如果字串包含小數位數元素,整數位數元素就不存在。 |
, | 特定文化特性的群組分隔符。 如果style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符符號可以出現在 中s |
. | 特定文化特性的小數點符號。 如果style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前文化特性的小數點符號可以出現在 中s 。 |
fractional-digits | 一連串的數位,範圍從 0 到 9,指定數位的小數部分。 如果style 包含旗標,NumberStyles.AllowDecimalPoint則小數位數可以出現在 中s 。 |
E | “e” 或 “E” 字元,表示值是以指數 (科學) 表示法表示。 如果style 包含旗標,參數s 可以表示指數表示法的數位NumberStyles.AllowExponent。 |
指數數位 | 指定指數的一系列數位範圍從 0 到 9。 |
注意
不論自變數的值style
為何,剖析作業都會忽略 中s
任何終止的 NUL (U+0000) 字元。
只有數位的字串 (對應至 NumberStyles.None 樣式) 在類型範圍內 Double 時一律會成功剖析。 可能存在但不需要存在於輸入字串中的其餘 System.Globalization.NumberStyles 成員控件元素。 下表指出個別 NumberStyles 旗標如何影響 中 s
可能存在的專案。
NumberStyles 值 | 除了數位之外允許 s 的專案 |
---|---|
None | 僅限 整數數字元素 。 |
AllowDecimalPoint | 小數點 (。) 和 小數位數 元素。 |
AllowExponent | 表示指數表示法的 「e」 或 「E」 字元。 此旗標本身 支援格式為E位數的值;需要額外的旗標,才能成功剖析具有正數或負號和小數點符號等元素的字串。 |
AllowLeadingWhite | 開頭的 s ws 元素。 |
AllowTrailingWhite | 結尾處的 s ws 元素。 |
AllowLeadingSign | 開頭的s 符號專案。 |
AllowTrailingSign | 結尾處的s 符號專案。 |
AllowParentheses | 以括弧括住數值形式的 sign 元素。 |
AllowThousands | 千位分隔符 (,) 元素。 |
AllowCurrencySymbol | 貨幣 ($) 元素。 |
Currency | 所有元素。 不過, s 不能代表十六進位數或指數表示法中的數位。 |
Float | 開頭或結尾的 s ws 元素,會在 開頭加上s 小數點 (.) 符號。 參數 s 也可以使用指數表示法。 |
Number | ws 、sign 、thousands 分隔符 (、) 和小數點 (.) 元素。 |
Any | 所有元素。 不過, s 不能代表十六進位數。 |
參數 s
會使用針對目前系統文化特性初始化的 物件中的 NumberFormatInfo 格式化資訊進行剖析。 如需詳細資訊,請參閱CurrentInfo。
一般而言,如果您傳遞 Double.Parse 方法所建立 Double.ToString 的字串,則會傳回原始 Double 值。 不過,由於精確度遺失,值可能不相等。 此外,嘗試剖析 或 Double.MaxValue 無法往返的字串表示Double.MinValue。 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowException。 在 .NET Core 3.0 和更新版本上,如果您嘗試剖析MinValue或嘗試剖MaxValue析 ,則會傳回 Double.NegativeInfinityDouble.PositiveInfinity。 下列範例提供說明。
string value;
value = Double.MinValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
value = Double.MaxValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// Format without the default precision.
value = Double.MinValue.ToString("G17");
try
{
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException)
{
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
open System
[<EntryPoint>]
let main _ =
let value = string Double.MinValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
let value = string Double.MaxValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
// Format without the default precision.
let value = Double.MinValue.ToString "G17"
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
0
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
Dim value As String
value = Double.MinValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
value = Double.MaxValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
' -1.79769313486232E+308 is outside the range of the Double type.
' 1.79769313486232E+308 is outside the range of the Double type.
' -1.79769313486232E+308
在 .NET Framework 和 .NET Core 2.2 和舊版上,如果s
超出數據類型的範圍Double,則Parse(String, NumberStyles)方法會OverflowException擲回 。
在 .NET Core 3.0 和更新版本上,當超出數據類型的範圍Double時s
,不會擲回例外狀況。 在大部分情況下, Parse(String, NumberStyles) 方法會傳回 Double.PositiveInfinity 或 Double.NegativeInfinity。 不過,有一組小的值會被視為比正或負無限大接近最大值或最小值 Double 。 在這些情況下,方法會傳 Double.MaxValue 回 或 Double.MinValue。
如果在剖析作業期間於 參數中 s
遇到分隔符,且適用的貨幣或數位十進位和群組分隔符相同,則剖析作業會假設分隔符是小數分隔符,而不是群組分隔符。 如需分隔符的詳細資訊,請參閱CurrencyDecimalSeparator、 NumberDecimalSeparatorCurrencyGroupSeparator、 和 NumberGroupSeparator。
另請參閱
適用於
Parse(String, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。
public:
static double Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static double Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<double>::Parse;
public static double Parse (string s, IFormatProvider provider);
public static double Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> double
Public Shared Function Parse (s As String, provider As IFormatProvider) As Double
參數
- s
- String
字串,其包含要轉換的數字。
- provider
- IFormatProvider
物件,提供關於 s
的特定文化特性格式資訊。
傳回
雙精確度浮點數,與 s
中指定的數值或符號相等。
實作
例外狀況
s
為 null
。
s
不是有效格式的數字。
僅 .NET Framework 和 .NET Core 2.2 和舊版:s
代表小於 Double.MinValue 或大於 Double.MaxValue 的數位。
範例
下列範例是 Web 窗體的按鈕 click 事件處理程式。 它會使用 屬性傳回的 HttpRequest.UserLanguages 陣列來判斷用戶的地區設定。 然後,它會具現化 CultureInfo 對應至該地區設定的物件。 NumberFormatInfo屬於該CultureInfo物件的 對象接著會傳遞至 方法,Parse(String, IFormatProvider)以將使用者的輸入轉換為Double值。
protected void OkToDouble_Click(object sender, EventArgs e)
{
string locale;
double number;
CultureInfo culture;
// Return if string is empty
if (String.IsNullOrEmpty(this.inputNumber.Text))
return;
// Get locale of web request to determine possible format of number
if (Request.UserLanguages.Length == 0)
return;
locale = Request.UserLanguages[0];
if (String.IsNullOrEmpty(locale))
return;
// Instantiate CultureInfo object for the user's locale
culture = new CultureInfo(locale);
// Convert user input from a string to a number
try
{
number = Double.Parse(this.inputNumber.Text, culture.NumberFormat);
}
catch (FormatException)
{
return;
}
catch (OverflowException)
{
return;
}
// Output number to label on web form
this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDouble_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDouble.Click
Dim locale As String
Dim culture As CultureInfo
Dim number As Double
' Return if string is empty
If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub
' Get locale of web request to determine possible format of number
If Request.UserLanguages.Length = 0 Then Exit Sub
locale = Request.UserLanguages(0)
If String.IsNullOrEmpty(locale) Then Exit Sub
' Instantiate CultureInfo object for the user's locale
culture = New CultureInfo(locale)
' Convert user input from a string to a number
Try
number = Double.Parse(Me.inputNumber.Text, culture.NumberFormat)
Catch ex As FormatException
Exit Sub
Catch ex As Exception
Exit Sub
End Try
' Output number to label on web form
Me.outputNumber.Text = "Number is " & number.ToString()
End Sub
備註
在 .NET Core 3.0 和更新版本中,無法表示的值會四捨五入或 PositiveInfinityNegativeInfinity IEEE 754 規格所需的值。 在舊版中,包括 .NET Framework,剖析太大而無法表示的值會導致失敗。
這個方法的多 Parse(String, IFormatProvider) 載通常用來將各種格式 Double 的文字轉換成值。 例如,它可以用來將使用者輸入的文字轉換成 HTML 文字框,轉換為數值。
參數s
是使用 和 NumberStyles.AllowThousands 旗標的組合NumberStyles.Float來解譯。 參數 s
可以包含 NumberFormatInfo.PositiveInfinitySymbol、 NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol 指定的文化 provider
特性,也可以包含格式的字串:
[ws][sign]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
選擇性元素會以方括弧括住, ([ 和 ]) 。 包含「數位」一詞的專案包含一系列範圍從 0 到 9 的數位字元。
元素 | 描述 |
---|---|
ws | 一系列的空格符。 |
簽署 | 負號符號 ( ) 或正負號符號 (+) 。 |
integral-digits | 一連串的數位,範圍從 0 到 9,指定數位的整數部分。 整數位數的執行可由群組分隔符分割。 例如,在某些文化特性中,逗號 (,) 分隔數千個群組。 如果字串包含小數位數元素,整數位數元素就不存在。 |
. | 特定文化特性的小數點符號。 |
fractional-digits | 一系列的數字,範圍從0到9,指定數位的小數部分。 |
E | “e” 或 “E” 字元,表示該值是以指數 (科學) 表示法表示。 |
指數數位 | 一系列數位,範圍從 0 到 9,指定指數。 |
如需數值格式的詳細資訊,請參閱 格式化類型 主題。
參數 provider
是實作, IFormatProvider 其 GetFormat 方法會傳回 NumberFormatInfo 物件,以提供解譯 格式 s
時所使用的特定文化特性資訊。 一般而言,它是 NumberFormatInfo 或 CultureInfo 物件。 如果 為 provider
null
或 NumberFormatInfo 無法取得 ,則會使用目前系統文化特性的格式資訊。
一般而言,如果您傳遞 Double.Parse 方法以呼叫 方法所建立的 Double.ToString 字串,則會傳回原始 Double 值。 不過,由於遺失精確度,值可能不相等。 此外,嘗試剖析 或 Double.MaxValue 的字串表示Double.MinValue無法來回。 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowException。 在 .NET Core 3.0 和更新版本上,如果您嘗試剖析MinValue或嘗試剖析 MaxValue,則會傳回 Double.NegativeInfinityDouble.PositiveInfinity。 下列範例提供說明。
string value;
value = Double.MinValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
value = Double.MaxValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// Format without the default precision.
value = Double.MinValue.ToString("G17");
try
{
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException)
{
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
open System
[<EntryPoint>]
let main _ =
let value = string Double.MinValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
let value = string Double.MaxValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
// Format without the default precision.
let value = Double.MinValue.ToString "G17"
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
0
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
Dim value As String
value = Double.MinValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
value = Double.MaxValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
' -1.79769313486232E+308 is outside the range of the Double type.
' 1.79769313486232E+308 is outside the range of the Double type.
' -1.79769313486232E+308
在 .NET Framework 和 .NET Core 2.2 和舊版上,如果 s
超出數據類型的範圍Double,方法會Parse(String, IFormatProvider)擲回 OverflowException。
在 .NET Core 3.0 和更新版本上,當 超出數據類型的範圍Double時s
,不會擲回例外狀況。 在大部分情況下,方法 Parse(String, IFormatProvider) 會傳回 Double.PositiveInfinity 或 Double.NegativeInfinity。 不過,有一組小的值會被視為比正或負無限大更接近最大值或最小值 Double 。 在這些情況下,方法會傳 Double.MaxValue 回 或 Double.MinValue。
如果在剖析作業期間於 參數中 s
遇到分隔符,且適用的貨幣或數位十進位和群組分隔符相同,則剖析作業會假設分隔符是小數分隔符,而不是群組分隔符。 如需分隔符的詳細資訊,請參閱CurrencyDecimalSeparator、 NumberDecimalSeparatorCurrencyGroupSeparator和 NumberGroupSeparator。
另請參閱
適用於
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
將UTF-8字元的範圍剖析為值。
public static double Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double
參數
- utf8Text
- ReadOnlySpan<Byte>
要剖析的UTF-8字元範圍。
- style
- NumberStyles
數字樣式的位元組合,可以存在於 中 utf8Text
。
- provider
- IFormatProvider
提供關於 utf8Text
之特定文化特性格式資訊的物件。
傳回
剖析 utf8Text
的結果。
實作
適用於
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。
public static double Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
public static double Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double
參數
- s
- ReadOnlySpan<Char>
字元範圍,其包含要轉換的數字。
- style
- NumberStyles
列舉值的位元組合,其表示 s
中可以存在的樣式項目。 所要指定一般值為 Float 和 AllowThousands 的組合。
- provider
- IFormatProvider
物件,其提供關於 s
的特定文化特性格式資訊。
傳回
雙精確度浮點數,與 s
中指定的數值或符號相等。
實作
例外狀況
s
不代表數字。
備註
在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入為 PositiveInfinity IEEE 754 規格所需的或 NegativeInfinity 。 在舊版中,包括 .NET Framework,剖析太大而無法表示導致失敗的值。
如果 s
超出數據類型的範圍Double,則如果 s
小於 Double.MinValue 且 Double.PositiveInfinitys
Double.MaxValue大於 ,則方法會傳回 。Double.NegativeInfinity
適用於
Parse(String, NumberStyles, IFormatProvider)
- 來源:
- Double.cs
- 來源:
- Double.cs
- 來源:
- Double.cs
使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。
public:
static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<double>::Parse;
public static double Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static double Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Double
參數
- s
- String
字串,其包含要轉換的數字。
- style
- NumberStyles
列舉值的位元組合,其表示 s
中可以存在的樣式項目。 所要指定一般值為 Float 和 AllowThousands 的組合。
- provider
- IFormatProvider
物件,其提供關於 s
的特定文化特性格式資訊。
傳回
雙精確度浮點數,與 s
中指定的數值或符號相等。
實作
例外狀況
s
為 null
。
s
不代表數字。
.NET Framework 和 .NET Core 2.2 和舊版:只s
代表小於 Double.MinValue 或大於 Double.MaxValue 的數位。
範例
下列範例說明如何使用 Parse(String, NumberStyles, IFormatProvider) 方法,將溫度值的數個 Temperature
字串表示指派給物件。
using System;
using System.Globalization;
public class Temperature
{
// Parses the temperature from a string. Temperature scale is
// indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
// of the string.
public static Temperature Parse(string s, NumberStyles styles,
IFormatProvider provider)
{
Temperature temp = new Temperature();
if (s.TrimEnd(null).EndsWith("'F"))
{
temp.Value = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
styles, provider);
}
else
{
if (s.TrimEnd(null).EndsWith("'C"))
temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
styles, provider);
else
temp.Value = Double.Parse(s, styles, provider);
}
return temp;
}
// Declare private constructor so Temperature so only Parse method can
// create a new instance
private Temperature() {}
protected double m_value;
public double Value
{
get { return m_value; }
private set { m_value = value; }
}
public double Celsius
{
get { return (m_value - 32) / 1.8; }
private set { m_value = value * 1.8 + 32; }
}
public double Fahrenheit
{
get {return m_value; }
}
}
public class TestTemperature
{
public static void Main()
{
string value;
NumberStyles styles;
IFormatProvider provider;
Temperature temp;
value = "25,3'C";
styles = NumberStyles.Float;
provider = CultureInfo.CreateSpecificCulture("fr-FR");
temp = Temperature.Parse(value, styles, provider);
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
temp.Fahrenheit, temp.Celsius);
value = " (40) 'C";
styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowParentheses;
provider = NumberFormatInfo.InvariantInfo;
temp = Temperature.Parse(value, styles, provider);
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
temp.Fahrenheit, temp.Celsius);
value = "5,778E03'C"; // Approximate surface temperature of the Sun
styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
NumberStyles.AllowExponent;
provider = CultureInfo.CreateSpecificCulture("en-GB");
temp = Temperature.Parse(value, styles, provider);
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"));
}
}
open System
open System.Globalization
// Declare private constructor so Temperature so only Parse method can create a new instance
type Temperature private () =
let mutable m_value = 0.
member _.Value
with get () = m_value
and private set (value) = m_value <- value
member _.Celsius
with get() = (m_value - 32.) / 1.8
and private set (value) = m_value <- value * 1.8 + 32.
member _.Fahrenheit =
m_value
// Parses the temperature from a string. Temperature scale is
// indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
// of the string.
static member Parse(s: string, styles: NumberStyles, provider: IFormatProvider) =
let temp = new Temperature()
if s.TrimEnd(null).EndsWith "'F" then
temp.Value <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
else
if s.TrimEnd(null).EndsWith "'C" then
temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
else
temp.Value <- Double.Parse(s, styles, provider)
temp
[<EntryPoint>]
let main _ =
let value = "25,3'C"
let styles = NumberStyles.Float
let provider = CultureInfo.CreateSpecificCulture "fr-FR"
let temp = Temperature.Parse(value, styles, provider)
printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."
let value = " (40) 'C"
let styles = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite ||| NumberStyles.AllowParentheses
let provider = NumberFormatInfo.InvariantInfo
let temp = Temperature.Parse(value, styles, provider)
printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."
let value = "5,778E03'C" // Approximate surface temperature of the Sun
let styles = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands ||| NumberStyles.AllowExponent
let provider = CultureInfo.CreateSpecificCulture "en-GB"
let temp = Temperature.Parse(value, styles, provider)
printfn $"{temp.Fahrenheit:N} degrees Fahrenheit equals {temp.Celsius:N} degrees Celsius."
0
Imports System.Globalization
Public Class Temperature
' Parses the temperature from a string. Temperature scale is
' indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
' of the string.
Public Shared Function Parse(s As String, styles As NumberStyles, _
provider As IFormatProvider) As Temperature
Dim temp As New Temperature()
If s.TrimEnd(Nothing).EndsWith("'F") Then
temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
styles, provider)
Else
If s.TrimEnd(Nothing).EndsWith("'C") Then
temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
styles, provider)
Else
temp.Value = Double.Parse(s, styles, provider)
End If
End If
Return temp
End Function
' Declare private constructor so Temperature so only Parse method can
' create a new instance
Private Sub New
End Sub
Protected m_value As Double
Public Property Value() As Double
Get
Return m_value
End Get
Private Set
m_value = Value
End Set
End Property
Public Property Celsius() As Double
Get
Return (m_value - 32) / 1.8
End Get
Private Set
m_value = Value * 1.8 + 32
End Set
End Property
Public ReadOnly Property Fahrenheit() As Double
Get
Return m_Value
End Get
End Property
End Class
Public Module TestTemperature
Public Sub Main
Dim value As String
Dim styles As NumberStyles
Dim provider As IFormatProvider
Dim temp As Temperature
value = "25,3'C"
styles = NumberStyles.Float
provider = CultureInfo.CreateSpecificCulture("fr-FR")
temp = Temperature.Parse(value, styles, provider)
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
temp.Fahrenheit, temp.Celsius)
value = " (40) 'C"
styles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite _
Or NumberStyles.AllowParentheses
provider = NumberFormatInfo.InvariantInfo
temp = Temperature.Parse(value, styles, provider)
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
temp.Fahrenheit, temp.Celsius)
value = "5,778E03'C" ' Approximate surface temperature of the Sun
styles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
NumberStyles.AllowExponent
provider = CultureInfo.CreateSpecificCulture("en-GB")
temp = Temperature.Parse(value, styles, provider)
Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"))
End Sub
End Module
備註
在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入為 PositiveInfinity IEEE 754 規格所需的或 NegativeInfinity 。 在舊版中,包括 .NET Framework,剖析太大而無法表示導致失敗的值。
參數 style
會定義樣式專案 (,例如空格符、千位分隔符,以及參數中 s
允許的貨幣符號) ,讓剖析作業成功。 它必須是列舉中的 NumberStyles 位旗標組合。 不支援下列 NumberStyles 成員:
參數 s
可以包含 NumberFormatInfo.PositiveInfinitySymbol、 NumberFormatInfo.NegativeInfinitySymbol或 NumberFormatInfo.NaNSymbol ,供 所指定的文化特性使用 provider
。 視 的值 style
而定,它也可以採用下列格式:
[ws][] [$sign][integral-digits,]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
以方括弧 ([ 和 ]) 框架的項目是選擇性的。 下表說明每個元素。
元素 | 描述 |
---|---|
ws | 一系列空格符。 如果 包含 旗標,則空格元可以出現在 的s 開頭,如果包含 NumberStyles.AllowTrailingWhite 旗標,則會出現在 結尾style s 。NumberStyles.AllowLeadingWhitestyle |
$ | 特定文化特性的貨幣符號。 字串中的位置是由 NumberFormatInfo.CurrencyNegativePattern 目前文化特性的 和 NumberFormatInfo.CurrencyPositivePattern 屬性所定義。 如果style 包含 NumberStyles.AllowCurrencySymbol 旗標,則目前文化特性的貨幣符號可能會出現在 中s 。 |
簽署 | 負號符號 ( ) 或正負號符號 (+) 。 如果 style 包含旗標,則符號可以出現在的s 開頭,如果包含 NumberStyles.AllowTrailingSign 旗標,則會出現在 的style s NumberStyles.AllowLeadingSign結尾。 如果包含 NumberStyles.AllowParentheses 旗標,則可以在 中使用s 括弧來表示負值style 。 |
整數數位 | 一系列的數字,範圍從0到9,指定數位的整數部分。 如果字串包含fractional-digits元素,整數數字元素就可能不存在。 |
, | 特定文化特性的群組分隔符。 如果style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符符號可能會出現在 中s |
. | 特定文化特性的小數點符號。 如果style 包含 NumberStyles.AllowDecimalPoint 旗標,則目前的文化特性小數點符號可能會出現在 中s 。 |
fractional-digits | 一系列的數字,範圍從0到9,指定數位的小數部分。 如果style 包含旗標,NumberStyles.AllowDecimalPoint則可以在 中s 顯示小數位數。 |
E | “e” 或 “E” 字元,表示該值是以指數 (科學) 表示法表示。 如果style 包含 NumberStyles.AllowExponent 旗標,參數s 可以代表指數表示法的數位。 |
指數數位 | 一系列數位,範圍從 0 到 9,指定指數。 |
注意
中任何終止的 NUL (U+0000) 字元 s
都會被剖析作業忽略,不論自變數的值 style
為何。
只有數位的字串 (對應至 NumberStyles.None 樣式) 一律會在類型範圍內 Double 成功剖析。 可能存在但不需要出現在輸入字串中的其餘 System.Globalization.NumberStyles 成員控制項專案。 下表指出個別 NumberStyles 旗標如何影響 中 s
可能存在的專案。
NumberStyles 值 | 除了數位之外, s 允許的專案 |
---|---|
None | 僅限 整數數字元素 。 |
AllowDecimalPoint | 小數點 (。) 和 小數位數元素 。 |
AllowExponent | 表示指數表示法的 「e」 或 「E」 字元。 此旗標本身 支援格式為E位數的值;需要額外的旗標,才能成功剖析具有正數或負號和小數點符號等元素的字串。 |
AllowLeadingWhite | 開頭的 s ws 元素。 |
AllowTrailingWhite | 結尾處的 s ws 元素。 |
AllowLeadingSign | 開頭的s 符號專案。 |
AllowTrailingSign | 結尾處的s 符號專案。 |
AllowParentheses | 以括弧括住數值形式的 sign 元素。 |
AllowThousands | 千位分隔符 (,) 元素。 |
AllowCurrencySymbol | 貨幣 ($) 元素。 |
Currency | 所有元素。 不過, s 不能代表十六進位數或指數表示法中的數位。 |
Float | 開頭或結尾的 s ws 元素,會在 開頭加上s 小數點 (.) 符號。 參數 s 也可以使用指數表示法。 |
Number | ws 、sign 、thousands 分隔符 (、) 和小數點 (.) 元素。 |
Any | 所有元素。 不過, s 不能代表十六進位數。 |
參數是實IFormatProvider作,其provider
GetFormat方法會NumberFormatInfo傳回 物件,該物件提供用來解譯 格式s
的文化特性特定資訊。 一般而言,它是 NumberFormatInfo 或 CultureInfo 物件。 如果 provider
為 null
或 NumberFormatInfo 無法取得 ,則會使用目前系統文化特性的格式資訊。
一般而言,如果您傳遞 Double.Parse 方法所建立 Double.ToString 的字串,則會傳回原始 Double 值。 不過,由於精確度遺失,值可能不相等。 此外,嘗試剖析 或 Double.MaxValue 無法往返的字串表示MinValue。 在 .NET Framework 和 .NET Core 2.2 和舊版上,它會擲回 OverflowException。 在 .NET Core 3.0 和更新版本上,如果您嘗試剖析MinValue或嘗試剖MaxValue析 ,則會傳回 Double.NegativeInfinityDouble.PositiveInfinity。 下列範例提供說明。
string value;
value = Double.MinValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
value = Double.MaxValue.ToString();
try {
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException) {
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// Format without the default precision.
value = Double.MinValue.ToString("G17");
try
{
Console.WriteLine(Double.Parse(value));
}
catch (OverflowException)
{
Console.WriteLine($"{value} is outside the range of the Double type.");
}
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
open System
[<EntryPoint>]
let main _ =
let value = string Double.MinValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
let value = string Double.MaxValue
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
// Format without the default precision.
let value = Double.MinValue.ToString "G17"
try
printfn $"{Double.Parse value}"
with :? OverflowException ->
printfn $"{value} is outside the range of the Double type."
0
// The example displays the following output:
// -1.79769313486232E+308 is outside the range of the Double type.
// 1.79769313486232E+308 is outside the range of the Double type.
// -1.79769313486232E+308
Dim value As String
value = Double.MinValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
value = Double.MaxValue.ToString()
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try
Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
' -1.79769313486232E+308 is outside the range of the Double type.
' 1.79769313486232E+308 is outside the range of the Double type.
' -1.79769313486232E+308
在 .NET Framework 和 .NET Core 2.2 和舊版上,如果 s
超出數據類型的範圍Double,則Parse(String, NumberStyles, IFormatProvider)方法會OverflowException擲回 。
在 .NET Core 3.0 和更新版本上,當超出數據類型的範圍Double時s
,不會擲回例外狀況。 在大部分情況下, Parse(String, NumberStyles, IFormatProvider) 方法會傳回 Double.PositiveInfinity 或 Double.NegativeInfinity。 不過,有一組小的值會被視為比正或負無限大接近最大值或最小值 Double 。 在這些情況下,方法會傳 Double.MaxValue 回 或 Double.MinValue。
如果在剖析作業期間於 參數中 s
遇到分隔符,且適用的貨幣或數位十進位和群組分隔符相同,則剖析作業會假設分隔符是小數分隔符,而不是群組分隔符。 如需分隔符的詳細資訊,請參閱CurrencyDecimalSeparator、 NumberDecimalSeparatorCurrencyGroupSeparator、 和 NumberGroupSeparator。
另請參閱
適用於
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應