Decimal.TryParse 方法

定義

將數字的字串表示,轉換為其相等的 DecimalConverts the string representation of a number to its Decimal equivalent. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

多載

TryParse(String, NumberStyles, IFormatProvider, Decimal)

使用指定的樣式和特定文化特性格式,將數字的字串表示轉換為其對等的 DecimalConverts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

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

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Char>, Decimal)

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, Decimal)

將數字的字串表示,轉換為其相等的 DecimalConverts the string representation of a number to its Decimal equivalent. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, NumberStyles, IFormatProvider, Decimal)

使用指定的樣式和特定文化特性格式,將數字的字串表示轉換為其對等的 DecimalConverts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。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] System::Decimal % result);
public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out decimal result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * decimal -> bool
Public Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Decimal) As Boolean

參數

s
String

要轉換的數字的字串表示。The string representation of the number to convert.

style
NumberStyles

列舉值的位元組合,其表示 s 所允許的格式。A bitwise combination of enumeration values that indicates the permitted format of s. 一般會指定的值是 NumberA typical value to specify is Number.

provider
IFormatProvider

物件,提供 s 的相關特定文化特性剖析資訊。An object that supplies culture-specific parsing information about s.

result
Decimal

當此方法傳回時,包含相當於 s 中所包含數值的 Decimal 數,或若轉換失敗,則傳回零。When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed. s 參數是 nullEmpty不是符合 style 格式規範的數字或代表小於 MinValue 或大於 MaxValue 的數字,則轉換會失敗。The conversion fails if the s parameter is null or Empty, is not a number in a format compliant with style, or represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都會被覆寫。This parameter is passed uininitialized; any value originally supplied in result is overwritten.

傳回

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

例外狀況

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

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

範例

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

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

// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Decimal.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 (Decimal.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 (Decimal.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 (Decimal.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 Decimal

' Parse currency value using en-GB culture.
value = "£1,097.63"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
culture = CultureInfo.CreateSpecificCulture("en-GB")
If Decimal.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 Decimal.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 Decimal.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 Decimal.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'.

備註

這個多載與 Decimal.Parse(String, NumberStyles, IFormatProvider) 方法不同,藉由傳回布林值,指出剖析作業是否成功,而不是傳回剖析的數值。This overload differs from the Decimal.Parse(String, NumberStyles, IFormatProvider) 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.

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 參數可能包含下列元素:Depending on the value of style, the s parameter may include the following elements:

atl-ws-01[$]簽訂[數位,] 數位 [. 小數數位] [e [sign] 數位] [ws][ws][$][sign][digits,]digits[.fractional-digits][e[sign]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.
digitsdigits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數數位fractional-digits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.

style 參數會指定 s 參數的允許格式,而且可以是一或多個使用位 OR 運算結合的 NumberStyles 列舉常數。The style parameter specifies the permitted format of the s parameter, and can be one or more NumberStyles enumerated constants combined using a bitwise OR operation. 如果 style 為 null,則會使用 NumberStyles.Number 樣式來解讀 sIf style is null, s is interpreted using the NumberStyles.Number style.

provider 參數是 IFormatProvider 的執行,例如 NumberFormatInfoCultureInfo 物件。The provider parameter is an IFormatProvider implementation such as a NumberFormatInfo or CultureInfo object. provider 參數提供用於剖析的特定文化特性資訊。The provider parameter supplies culture-specific information used in parsing. 如果 providernull,則會使用執行緒目前的文化特性。If provider is null, the thread current culture is used.

Decimal 物件的精確度為29位數。A Decimal object has 29 digits of precision. 如果 s 代表具有超過29位數的數位,但有小數部分,而且在 MaxValueMinValue的範圍內,則會使用四捨五入到最接近的數位,將數值四捨五入、不截斷為29位數。If s represents a number that has more than 29 digits, but has a fractional part and is within the range of MaxValue and MinValue, the number is rounded, not truncated, to 29 digits using rounding to nearest.

如果在剖析作業期間于 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.

另請參閱

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

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。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] System::Decimal % result);
public static bool TryParse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out decimal result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * decimal -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Decimal) As Boolean

參數

s
ReadOnlySpan<Char>

範圍,其包含代表所要轉換數字的字元。A span containing the characters representing the number to convert.

style
NumberStyles

列舉值的位元組合,其表示 s 所允許的格式。A bitwise combination of enumeration values that indicates the permitted format of s. 一般會指定的值是 NumberA typical value to specify is Number.

provider
IFormatProvider

物件,提供 s 的相關特定文化特性剖析資訊。An object that supplies culture-specific parsing information about s.

result
Decimal

當此方法傳回時,包含相當於 s 中所包含數值的 Decimal 數,或若轉換失敗,則傳回零。When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed. s 參數是 nullEmpty不是符合 style 格式規範的數字或代表小於 MinValue 或大於 MaxValue 的數字,則轉換會失敗。The conversion fails if the s parameter is null or Empty, is not a number in a format compliant with style, or represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都會被覆寫。This parameter is passed uininitialized; any value originally supplied in result is overwritten.

傳回

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

TryParse(ReadOnlySpan<Char>, Decimal)

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

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

參數

s
ReadOnlySpan<Char>

範圍,其包含代表所要轉換數字的字元。A span containing the characters representing the number to convert.

result
Decimal

當此方法傳回時,包含相當於 s 中所包含數值的 Decimal 數,或若轉換失敗,則傳回零。When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed. s 參數是 nullEmpty不是符合 style 格式規範的數字或代表小於 MinValue 或大於 MaxValue 的數字,則轉換會失敗。The conversion fails if the s parameter is null or Empty, is not a number in a format compliant with style, or represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都會被覆寫。This parameter is passed uininitialized; any value originally supplied in result is overwritten.

傳回

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

TryParse(String, Decimal)

將數字的字串表示,轉換為其相等的 DecimalConverts the string representation of a number to its Decimal equivalent. 傳回值,該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

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

參數

s
String

要轉換的數字的字串表示。The string representation of the number to convert.

result
Decimal

當此方法傳回時,包含相當於 s 中所包含數值的 Decimal 數,或若轉換失敗,則傳回零。When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed. 如果 s 參數為 nullEmpty、不是有效格式的數字,或者代表小於 MinValue 或大於 MaxValue 的數字,這項轉換就會失敗。The conversion fails if the s parameter is null or Empty, is not a number in a valid format, or represents a number less than MinValue or greater than MaxValue. 這個參數未初始化便傳遞,result 中原始提供的任何值都會被覆寫。This parameter is passed uininitialized; any value originally supplied in result is overwritten.

傳回

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

範例

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

string value;
decimal number;

// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Decimal.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);      

// Parse a floating-point value with a currency symbol and a 
// thousands separator.
value = "$1,643.57";
if (Decimal.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);   

// Parse value in exponential notation.
value = "-1.643e6";
if (Decimal.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);   

// Parse a negative integer value.
value = "-1689346178821";
if (Decimal.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);   
// The example displays the following output to the console:
//       1643.57
//       Unable to parse '$1,643.57'.
//       Unable to parse '-1.643e6'.
//       -1689346178821      
Dim value As String
Dim number As Decimal

' Parse a floating-point value with a thousands separator.
value = "1,643.57"
If Decimal.TryParse(value, number) Then
   Console.WriteLine(number)
Else
   Console.WriteLine("Unable to parse '{0}'.", value)      
End If   

' Parse a floating-point value with a currency symbol and a 
' thousands separator.
value = "$1,643.57"
If Decimal.TryParse(value, number) Then
   Console.WriteLine(number)  
Else
   Console.WriteLine("Unable to parse '{0}'.", value)   
End If

' Parse value in exponential notation.
value = "-1.643e6"
If Decimal.TryParse(value, number)
   Console.WriteLine(number)
Else
   Console.WriteLine("Unable to parse '{0}'.", value)   
End If

' Parse a negative integer value.
value = "-1689346178821"
If Decimal.TryParse(value, number)
   Console.WriteLine(number)
Else
   Console.WriteLine("Unable to parse '{0}'.", value)   
End If
' The example displays the following output to the console:
'       1643.57
'       Unable to parse '$1,643.57'.
'       Unable to parse '-1.643e6'.
'       -1689346178821      

備註

這個多載與 Decimal.Parse(String) 方法不同,藉由傳回布林值,指出剖析作業是否成功,而不是傳回剖析的數值。This overload differs from the Decimal.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 包含下列格式的數位:Parameter s contains a number of the form:

atl-ws-01簽訂[數位,] 數位 [. 小數位數] [ws][ws][sign][digits,]digits[.fractional-digits][ws]

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

項目Element 描述Description
wsws 選擇性的空白字元。Optional white space.
簽署sign 選擇性的正負號。An optional sign.
digitsdigits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.
, 文化特性特定的千位分隔符號。A culture-specific thousands separator symbol.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數數位fractional-digits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.

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

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

如有必要,s 的值會使用四捨五入到最接近的來進行舍入。If necessary, the value of s is rounded using rounding to nearest.

Decimal 物件的精確度為29位數。A Decimal object has 29 digits of precision. 如果 s 代表具有超過29位數的數位,但有小數部分,而且在 MaxValueMinValue的範圍內,則會使用四捨五入到最接近的數位,將數值四捨五入、不截斷為29位數。If s represents a number that has more than 29 digits, but has a fractional part and is within the range of MaxValue and MinValue, the number is rounded, not truncated, to 29 digits using rounding to nearest.

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

另請參閱

適用於