Decimal.Parse 方法

定义

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts the string representation of a number to its Decimal equivalent.

重载

Parse(String, NumberStyles, IFormatProvider)

使用指定样式和区域性特定格式将数字的字符串表示形式转换为其 Decimal 等效项。Converts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format.

Parse(String, IFormatProvider)

使用指定的区域性特定格式信息将数字的字符串表示形式转换为其 Decimal 等效项。Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information.

Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效 DecimalConverts the string representation of a number in a specified style to its Decimal equivalent.

Parse(String)

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts the string representation of a number to its Decimal equivalent.

Parse(String, NumberStyles, IFormatProvider)

使用指定样式和区域性特定格式将数字的字符串表示形式转换为其 Decimal 等效项。Converts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format.

public:
 static System::Decimal Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public static decimal Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> decimal
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Decimal

参数

s
String

要转换的数字的字符串表示形式。The string representation of the number to convert.

style
NumberStyles

NumberStyles 值的按位组合,指示可出现在 s 中的样式元素。A bitwise combination of NumberStyles values that indicates the style elements that can be present in s. 要指定的一个典型值为 NumberA typical value to specify is Number.

provider
IFormatProvider

一个 IFormatProvider 对象,用于提供有关 s 格式的区域性特定信息。An IFormatProvider object that supplies culture-specific information about the format of s.

返回

Decimal 数,它与 sstyle 所指定的 provider 中包含的数字等效。The Decimal number equivalent to the number contained in s as specified by style and provider.

异常

s 的格式不正确。s is not in the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字。s represents a number less than MinValue or greater than MaxValue.

snulls is null.

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

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

示例

下面的示例使用各种 styleprovider 参数来分析 Decimal 值的字符串表示形式。The following example uses a variety of style and provider parameters to parse the string representations of Decimal values.

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

// Parse string using "." as the thousands separator 
// and " " as the decimal separator. 
value = "892 694,12";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
provider = new CultureInfo("fr-FR");

number = Decimal.Parse(value, style, provider);  
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays: 
//    892 694,12' converted to 892694.12.

try
{
   number = Decimal.Parse(value, style, CultureInfo.InvariantCulture);  
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}   
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays: 
//    Unable to parse '892 694,12'.  

// Parse string using "$" as the currency symbol for en-GB and  
// en-us cultures.
value = "$6,032.51";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
provider = new CultureInfo("en-GB");

try
{
   number = Decimal.Parse(value, style, provider);  
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}   
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays: 
//    Unable to parse '$6,032.51'.

provider = new CultureInfo("en-US");
number = Decimal.Parse(value, style, provider);  
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays: 
//    '$6,032.51' converted to 6032.51.
Dim value As String
Dim number As Decimal
Dim style As NumberStyles
Dim provider As CultureInfo

' Parse string using "." as the thousands separator 
' and " " as the decimal separator. 
value = "892 694,12"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands
provider = New CultureInfo("fr-FR")

number = Decimal.Parse(value, style, provider)  
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays: 
'    892 694,12' converted to 892694.12.

Try
   number = Decimal.Parse(value, style, CultureInfo.InvariantCulture)  
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays: 
'    Unable to parse '892 694,12'.  

' Parse string using "$" as the currency symbol for en-GB and
' en-us cultures.
value = "$6,032.51"
style = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
provider = New CultureInfo("en-GB")

Try
   number = Decimal.Parse(value, style, provider)  
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays: 
'    Unable to parse '$6,032.51'.

provider = New CultureInfo("en-US")
number = Decimal.Parse(value, style, provider)  
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays: 
'    '$6,032.51' converted to 6032.51.

注解

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
$ 区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由 provider 参数的 GetFormat 方法返回的 NumberFormatInfo 对象的 CurrencyNegativePatternCurrencyPositivePattern 属性定义。Its position in the string is defined by the CurrencyNegativePattern and CurrencyPositivePattern properties of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. 如果 style 包含 NumberStyles.AllowCurrencySymbol 标志,货币符号可以出现在 s 中。The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
wsws 可选空白。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 标志,则空格可以出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingWhite 标志,则它可以出现在 s 的末尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
signsign 一个可选的符号。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 标志,则符号会出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingSign 标志,则它可以出现在 s 的末尾处。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 标志,则可以在 s 中使用括号来表示负值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digitsdigits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9.
, 区域性特定的千位分隔符。A culture-specific thousands separator symbol. 如果 style 包括 NumberStyles.AllowThousands 标志,则 provider 定义的区域性的千位分隔符可以出现在 s 中。The thousands separator of the culture defined by provider can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 区域性特定的小数点符号。A culture-specific decimal point symbol. 如果 style 包括 NumberStyles.AllowDecimalPoint 标志,则 provider 定义的区域性的小数点符号可以出现在 s 中。The decimal point symbol of the culture defined by provider can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsfractional-digits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9. 仅当 style 包含 NumberStyles.AllowDecimalPoint 标志时,小数位才能出现在 s 中。Fractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag.
ee "E" 或 "E" 字符,指示值以指数表示法表示。The 'e' or 'E' character, which indicates that the value is represented in exponential notation. 如果 style 包含 NumberStyles.AllowExponent 标志,则 s 参数可以表示指数表示法中的数字。The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

备注

无论 style 参数的值是什么,分析操作都将忽略 s 中任何终止的 NUL (U + 0000)字符。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

只有数字(对应于 None 样式)的字符串在 Decimal 类型的范围内时才会成功进行分析。A string with digits only (which corresponds to the None style) always parses successfully if it is in the range of the Decimal type. 其余 NumberStyles 成员控制可能但不要求出现在输入字符串中的元素。The remaining NumberStyles members control elements that may be but are not required to be present in the input string. 下表指示单个 NumberStyles 成员如何影响可能出现在 s中的元素。The following table indicates how individual NumberStyles members affect the elements that may be present in s.

NumberStyles 值NumberStyles value 除数字外允许在 s 中使用的元素Elements permitted in s in addition to digits
None 仅限数字元素。The digits element only.
AllowDecimalPoint .The . 小数位数元素。and fractional-digits elements.
AllowExponent s 参数还可以使用指数表示法。The s parameter can also use exponential notation. 此标志支持格式为 E**位的值;若要成功地分析具有正数或负号和小数点符号等元素的字符串,需要其他标志。This flag supports values in the form digitsEdigits; additional flags are needed to successfully parse strings with elements such as positive or negative signs and decimal point symbols.
AllowLeadingWhite s开头的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s末尾的ws元素。The ws element at the end of s.
AllowLeadingSign s开头的sign元素。The sign element at the beginning of s.
AllowTrailingSign s末尾的sign元素。The sign element at the end of s.
AllowParentheses 用括号括起数值的符号元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 元素。The , element.
AllowCurrencySymbol $ 元素。The $ element.
Currency 全部。All. s 参数不能表示十六进制数或以指数表示法表示的数字。The s parameter cannot represent a hexadecimal number or a number in exponential notation.
Float 位于 s开头或结尾处的ws元素,在 s的开头处进行签名,并且为 The ws element at the beginning or end of s, sign at the beginning of s, and the . 符号开头。symbol. s 参数还可以使用指数表示法。The s parameter can also use exponential notation.
Number wssign、、The ws, sign, ,, and . 位置。elements.
Any s 之外的所有样式不能表示十六进制数。All styles, except s cannot represent a hexadecimal number.

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.

另请参阅

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

使用指定样式和区域性特定格式将数字的范围表示形式转换为其 Decimal 等效项。Converts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format.

public static decimal Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Number, IFormatProvider provider = null);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> decimal
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Number, Optional provider As IFormatProvider = null) As Decimal

参数

s
ReadOnlySpan<Char>

包含表示要转换的数字的字符的范围。The span containing the characters representing the number to convert.

style
NumberStyles

NumberStyles 值的按位组合,指示可出现在 s 中的样式元素。A bitwise combination of NumberStyles values that indicates the style elements that can be present in s. 要指定的一个典型值为 NumberA typical value to specify is Number.

provider
IFormatProvider

一个 IFormatProvider 对象,用于提供有关 s 格式的区域性特定信息。An IFormatProvider object that supplies culture-specific information about the format of s.

返回

Decimal 数,它与 sstyle 所指定的 provider 中包含的数字等效。The Decimal number equivalent to the number contained in s as specified by style and provider.

Parse(String, IFormatProvider)

使用指定的区域性特定格式信息将数字的字符串表示形式转换为其 Decimal 等效项。Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information.

public:
 static System::Decimal Parse(System::String ^ s, IFormatProvider ^ provider);
public static decimal Parse (string s, IFormatProvider provider);
static member Parse : string * IFormatProvider -> decimal
Public Shared Function Parse (s As String, provider As IFormatProvider) As Decimal

参数

s
String

要转换的数字的字符串表示形式。The string representation of the number to convert.

provider
IFormatProvider

一个 IFormatProvider,它提供有关 s 的区域性特定分析信息。An IFormatProvider that supplies culture-specific parsing information about s.

返回

Decimal 数,它与由 s 所指定的 provider 中包含的数字等效。The Decimal number equivalent to the number contained in s as specified by provider.

异常

snulls is null.

s 的格式不正确。s is not of the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字。s represents a number less than MinValue or greater than MaxValue.

示例

下面的示例是 Web 窗体的按钮单击事件处理程序。The following example is the button click event handler of a Web form. 它使用 HttpRequest.UserLanguages 属性返回的数组来确定用户的区域设置。It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. 然后,它将实例化与该区域设置相对应的 CultureInfo 对象。It then instantiates a CultureInfo object that corresponds to that locale. 然后,将属于该 CultureInfo 对象的 NumberFormatInfo 对象传递到 Parse(String, IFormatProvider) 方法,以将用户的输入转换为 Decimal 值。The NumberFormatInfo object that belongs to that CultureInfo object is then passed to the Parse(String, IFormatProvider) method to convert the user's input to a Decimal value.

protected void OkToDecimal_Click(object sender, EventArgs e)
{
   string locale;
   decimal 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 = Decimal.Parse(this.inputNumber.Text, culture.NumberFormat);
   }
   catch (FormatException)
   {
      return;
   }
   catch (Exception)
   {
      return;
   }
   // Output number to label on web form
   this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDecimal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDecimal.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Decimal

   ' 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 = Decimal.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

注解

Parse(String, IFormatProvider) 方法的此重载通常用于将可通过多种方式设置格式的文本转换为 Decimal 值。This overload of the Parse(String, IFormatProvider) method is commonly used to convert text that can be formatted in a variety of ways to a Decimal value. 例如,它可用于将用户输入的文本转换为一个数字值。For example, it can be used to convert the text entered by a user into an HTML text box to a numeric value.

s 参数包含如下格式:The s parameter 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 样式对 s 参数进行解释。The s parameter is interpreted using the NumberStyles.Number style. 这意味着允许使用空格和千位分隔符,但不允许货币符号。This means that white space and thousands separators are allowed but currency symbols are not. 若要显式定义可出现在 s中的元素(如货币符号、千位分隔符和空格),请使用 Decimal.Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use the Decimal.Parse(String, NumberStyles, IFormatProvider) method.

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.

另请参阅

Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效 DecimalConverts the string representation of a number in a specified style to its Decimal equivalent.

public:
 static System::Decimal Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static decimal Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> decimal
Public Shared Function Parse (s As String, style As NumberStyles) As Decimal

参数

s
String

要转换的数字的字符串表示形式。The string representation of the number to convert.

style
NumberStyles

NumberStyles 值的按位组合,指示可出现在 s 中的样式元素。A bitwise combination of NumberStyles values that indicates the style elements that can be present in s. 要指定的一个典型值为 NumberA typical value to specify is Number.

返回

Decimal 数,它与由 s 所指定的 style 中包含的数字等效。The Decimal number equivalent to the number contained in s as specified by style.

异常

snulls is null.

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

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

s 的格式不正确。s is not in the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字s represents a number less than MinValue or greater than MaxValue

示例

下面的代码示例使用 Parse(String, NumberStyles) 方法,使用 en-us 区域性分析 Decimal 值的字符串表示形式。The following code example uses the Parse(String, NumberStyles) method to parse the string representations of Decimal values using the en-US culture.

string value;
decimal number;
NumberStyles style;

// Parse string with a floating point value using NumberStyles.None. 
value = "8694.12";
style = NumberStyles.None;
try
{
   number = Decimal.Parse(value, style);  
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
//    Unable to parse '8694.12'.

// Parse string with a floating point value and allow decimal point. 
style = NumberStyles.AllowDecimalPoint;
number = Decimal.Parse(value, style);  
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    '8694.12' converted to 8694.12.

// Parse string with negative value in parentheses
value = "(1,789.34)";
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | 
        NumberStyles.AllowParentheses; 
number = Decimal.Parse(value, style);  
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    '(1,789.34)' converted to -1789.34.

// Parse string using Number style
value = " -17,623.49 ";
style = NumberStyles.Number;
number = Decimal.Parse(value, style);  
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
//    ' -17,623.49 ' converted to -17623.49.
Dim value As String
Dim number As Decimal
Dim style As NumberStyles

' Parse string with a floating point value using NumberStyles.None. 
value = "8694.12"
style = NumberStyles.None
Try
   number = Decimal.Parse(value, style)  
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
'    Unable to parse '8694.12'.

' Parse string with a floating point value and allow decimal point. 
style = NumberStyles.AllowDecimalPoint
number = Decimal.Parse(value, style)  
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    '8694.12' converted to 8694.12.

' Parse string with negative value in parentheses
value = "(1,789.34)"
style = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
        NumberStyles.AllowParentheses 
number = Decimal.Parse(value, style)  
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    '(1,789.34)' converted to -1789.34.

' Parse string using Number style
value = " -17,623.49 "
style = NumberStyles.Number
number = Decimal.Parse(value, style)  
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    ' -17,623.49 ' converted to -17623.49.

注解

style 参数定义在 s 参数中允许的样式元素(如千位分隔符、空格和货币符号),以便分析操作成功。The style parameter defines the style elements (such as thousands separators, white space, and currency symbols) that are allowed in 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 的开头,如果 style 包含 NumberStyles.AllowTrailingWhite 标志,则它可以出现在 s 的末尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由当前区域性的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果 style 包含 NumberStyles.AllowCurrencySymbol 标志,当前区域性的货币符号可以出现在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
signsign 一个可选的符号。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 标志,则符号会出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingSign 标志,则它可以出现在 s 的末尾处。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 标志,则可以在 s 中使用括号来表示负值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digitsdigits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9.
, 区域性特定的千位分隔符。A culture-specific thousands separator symbol. 如果 style 包含 NumberStyles.AllowThousands 标志,当前区域性的千位分隔符可以出现在 s 中。The current culture's thousands separator can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 区域性特定的小数点符号。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 标志,当前区域性的小数点符号会出现在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsfractional-digits 介于0到9之间的一系列数字。A sequence of digits ranging from 0 to 9. 仅当 style 包含 NumberStyles.AllowDecimalPoint 标志时,小数位才能出现在 s 中。Fractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag.
ee "E" 或 "E" 字符,指示值以指数表示法表示。The 'e' or 'E' character, which indicates that the value is represented in exponential notation. 如果 style 包含 NumberStyles.AllowExponent 标志,则 s 参数可以表示指数表示法中的数字。The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

备注

无论 style 参数的值是什么,分析操作都将忽略 s 中任何终止的 NUL (U + 0000)字符。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

只有数字(对应于 None 样式)的字符串在 Decimal 类型的范围内时才会成功进行分析。A string with digits only (which corresponds to the None style) always parses successfully if it is in the range of the Decimal type. 其余 NumberStyles 成员控制可能但不要求出现在输入字符串中的元素。The remaining NumberStyles members control elements that may be but are not required to be present in the input string. 下表指示单个 NumberStyles 成员如何影响可能出现在 s中的元素。The following table indicates how individual NumberStyles members affect the elements that may be present in s.

NumberStyles 值NumberStyles value 除数字外允许在 s 中使用的元素Elements permitted in s in addition to digits
None 仅限数字元素。The digits element only.
AllowDecimalPoint .The . 小数位数元素。and fractional-digits elements.
AllowExponent s 参数还可以使用指数表示法。The s parameter can also use exponential notation. 此标志支持格式为 E**位的值;若要成功地分析具有正数或负号和小数点符号等元素的字符串,需要其他标志。This flag supports values in the form digitsEdigits; additional flags are needed to successfully parse strings with elements such as positive or negative signs and decimal point symbols.
AllowLeadingWhite s开头的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s末尾的ws元素。The ws element at the end of s.
AllowLeadingSign s开头的sign元素。The sign element at the beginning of s.
AllowTrailingSign s末尾的sign元素。The sign element at the end of s.
AllowParentheses 用括号括起数值的符号元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 元素。The , element.
AllowCurrencySymbol $ 元素。The $ element.
Currency 全部。All. s 参数不能表示十六进制数或以指数表示法表示的数字。The s parameter cannot represent a hexadecimal number or a number in exponential notation.
Float s开头或结尾处的ws元素、s开头的符号. 符号。The ws element at the beginning or end of s, sign at the beginning of s, and the . symbol. s 参数还可以使用指数表示法。The s parameter can also use exponential notation.
Number wssign,. 元素。The ws, sign, , and . elements.
Any s 之外的所有样式不能表示十六进制数。All styles, except s cannot represent a hexadecimal number.

使用为当前系统区域性初始化的 NumberFormatInfo 对象中的格式设置信息对 s 参数进行分析。The s parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture. 有关详细信息,请参阅 CurrentInfoFor more information, see CurrentInfo.

Decimal 的精度为29位。A Decimal 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 参数中遇到分隔符,styles 包括 NumberStyles.AllowThousandsNumberStyles.AllowDecimalPoint 值,适用的货币或小数和组分隔符相同,则分析操作假定分隔符是小数点分隔符,而不是组分隔符。If a separator is encountered in the s parameter during a parse operation, styles includes the NumberStyles.AllowThousands and NumberStyles.AllowDecimalPoint values, 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.

另请参阅

Parse(String)

将数字的字符串表示形式转换为它的等效 Decimal 表示形式。Converts the string representation of a number to its Decimal equivalent.

public:
 static System::Decimal Parse(System::String ^ s);
public static decimal Parse (string s);
static member Parse : string -> decimal
Public Shared Function Parse (s As String) As Decimal

参数

s
String

要转换的数字的字符串表示形式。The string representation of the number to convert.

返回

s 中包含的数字的等效值。The equivalent to the number contained in s.

异常

snulls is null.

s 的格式不正确。s is not in the correct format.

s 表示一个小于 MinValue 或大于 MaxValue 的数字。s represents a number less than MinValue or greater than MaxValue.

示例

下面的代码示例使用 Parse(String) 方法来分析 Decimal 值的字符串表示形式。The following code example uses the Parse(String) method to parse string representations of Decimal values.

string value;
decimal number;
// Parse an integer with thousands separators. 
value = "16,523,421";
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays: 
//    16,523,421' converted to 16523421.

// Parse a floating point value with thousands separators
value = "25,162.1378";
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays: 
//    25,162.1378' converted to 25162.1378.

// Parse a floating point number with US currency symbol.
value = "$16,321,421.75";
try
{
   number = Decimal.Parse(value);
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}   
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays:
//    Unable to parse '$16,321,421.75'.   

// Parse a number in exponential notation
value = "1.62345e-02";
try
{
   number = Decimal.Parse(value);
   Console.WriteLine("'{0}' converted to {1}.", value, number);
}   
catch (FormatException)
{
   Console.WriteLine("Unable to parse '{0}'.", value);
}
// Displays: 
//    Unable to parse '1.62345e-02'. 
Dim value As String
Dim number As Decimal

' Parse an integer with thousands separators. 
value = "16,523,421"
number = Decimal.Parse(value)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays: 
'    16,523,421' converted to 16523421.

' Parse a floating point value with thousands separators
value = "25,162.1378"
number = Decimal.Parse(value)
Console.WriteLine("'{0}' converted to {1}.", value, number)
' Displays:
'    25,162.1378' converted to 25162.1378.

' Parse a floating point number with US currency symbol.
value = "$16,321,421.75"
Try
   number = Decimal.Parse(value)
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays:
'    Unable to parse '$16,321,421.75'.  

' Parse a number in exponential notation
value = "1.62345e-02"
Try
   number = Decimal.Parse(value)
   Console.WriteLine("'{0}' converted to {1}.", value, number)
Catch e As FormatException
   Console.WriteLine("Unable to parse '{0}'.", value)
End Try
' Displays: 
'    Unable to parse '1.62345e-02'. 

注解

参数 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.Parse(String, NumberStyles)Decimal.Parse(String, NumberStyles, IFormatProvider) 方法。To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use either the Decimal.Parse(String, NumberStyles) or the Decimal.Parse(String, NumberStyles, IFormatProvider) method.

参数 s 使用为当前系统区域性初始化的 NumberFormatInfo 中的格式设置信息进行分析。Parameter s is parsed using the formatting information in a NumberFormatInfo initialized for the current system culture. 有关详细信息,请参阅 CurrentInfoFor more information, see CurrentInfo. 若要使用其他某个区域性的格式设置信息分析字符串,请使用 Decimal.Parse(String, IFormatProvider)Decimal.Parse(String, NumberStyles, IFormatProvider) 方法。To parse a string using the formatting information of some other culture, use the Decimal.Parse(String, IFormatProvider) or Decimal.Parse(String, NumberStyles, IFormatProvider) method.

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

Decimal 的精度为29位。A Decimal 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.

另请参阅

适用于