Decimal.TryParse 方法

定义

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts 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)

使用指定样式和区域性特定格式将数字的字符串表示形式转换为其 Decimal 等效项。Converts 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)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts 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)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts 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)

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts 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)

使用指定样式和区域性特定格式将数字的字符串表示形式转换为其 Decimal 等效项。Converts 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.

返回

如果 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. 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:

根据 style 的值,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]

方括号 ([ and ]) 中的元素是可选的。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.
signsign 一个可选的符号。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.

style 参数指定 s 参数的允许格式,可以是使用按位 "或" 运算组合在一起的一个或多个 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)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts 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.

返回

如果 true 成功转换,则为 s;否则为 falsetrue if s was converted successfully; otherwise, false.

TryParse(ReadOnlySpan<Char>, Decimal)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts 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.

返回

如果 true 成功转换,则为 s;否则为 falsetrue if s was converted successfully; otherwise, false.

TryParse(String, Decimal)

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts 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.

返回

如果 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. 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:

[ws][sign][digits,]digits[.fractional-digits][ws][ws][sign][digits,]digits[.fractional-digits][ws]

方括号 ([ and ]) 中的元素是可选的。Elements in square brackets ([ and ]) are optional. 下表对每个元素进行了描述。The following table describes each element.

元素Element 说明Description
wsws 可选空白。Optional white space.
signsign 一个可选的符号。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.

使用 NumberStyles.Number 样式解释参数 sParameter 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.

另请参阅

适用于