Decimal.TryParse Decimal.TryParse Decimal.TryParse Decimal.TryParse Method

定義

將數字的字串表示,轉換為其相等的 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) TryParse(String, NumberStyles, IFormatProvider, Decimal) TryParse(String, NumberStyles, IFormatProvider, Decimal) 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) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Decimal) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Decimal) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Decimal)
TryParse(ReadOnlySpan<Char>, Decimal) TryParse(ReadOnlySpan<Char>, Decimal) TryParse(ReadOnlySpan<Char>, Decimal) TryParse(ReadOnlySpan<Char>, Decimal)
TryParse(String, Decimal) TryParse(String, Decimal) TryParse(String, Decimal) 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) TryParse(String, NumberStyles, IFormatProvider, Decimal) TryParse(String, NumberStyles, IFormatProvider, Decimal) 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 String String String

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

style
NumberStyles NumberStyles NumberStyles NumberStyles

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

provider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

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

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

傳回

如果 true 轉換成功,則為 s,否則為 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. 這樣就不需要使用例外狀況處理來測試FormatException不正確s事件,而且無法成功剖析。It 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參數格式,讓剖析作業成功。 styleThe 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:

[ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][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. s 如果style包含旗NumberStyles.AllowLeadingWhite標,空白字元可能會出現在開頭。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. s 如果style包含旗NumberStyles.AllowTrailingWhite標,它可以出現在的結尾。It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是NumberFormatInfo.CurrencyNegativePatternprovider參數的NumberFormatInfo.CurrencyPositivePattern IFormatProvider.GetFormat方法所傳回NumberFormatInfo之物件的或屬性所定義。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. 如果s style包含旗標,貨幣符號可能會出現在中。NumberStyles.AllowCurrencySymbolThe 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-digitsfractional-digits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.

參數會指定s參數的允許格式,而且可以是使用位 or 運算結合NumberStyles的一或多個列舉常數。 styleThe 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, s則會使用NumberStyles.Number樣式來加以解讀。If style is null, s is interpreted using the NumberStyles.Number style.

參數是一個NumberFormatInfo執行,例如或CultureInfo物件。 IFormatProvider providerThe 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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

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

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

參數

傳回

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

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

參數

傳回

TryParse(String, Decimal) TryParse(String, Decimal) TryParse(String, Decimal) 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 String String String

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

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

傳回

如果 true 轉換成功,則為 s,否則為 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. 這樣就不需要使用例外狀況處理來測試FormatException不正確s事件,而且無法成功剖析。It 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:

[ws][sign][digits,]digits[.fractional-digits][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-digitsfractional-digits 範圍從0到9的數位序列。A sequence of digits ranging from 0 to 9.

使用樣式來解讀參數sNumberStyles.NumberParameter 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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於