Decimal.Parse 方法

定義

將數字的字串表示,轉換為其相等的 DecimalConverts the string representation of a number to its Decimal equivalent.

多載

Parse(String, NumberStyles, IFormatProvider)

使用指定的樣式和特定文化特性格式,將數字的字串表示轉換為其對等的 DecimalConverts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts the span representation of a number to its Decimal equivalent using the specified style and culture-specific format.

Parse(String, IFormatProvider)

使用指定的特定文化特性格式資訊,將數字的字串表示轉換為其對等的 DecimalConverts 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)

將數字的字串表示,轉換為其相等的 DecimalConverts the string representation of a number to its Decimal equivalent.

Parse(String, NumberStyles, IFormatProvider)

使用指定的樣式和特定文化特性格式,將數字的字串表示轉換為其對等的 DecimalConverts 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 數字,等於包含在 s 中的數字,如同 styleprovider 所指定。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:

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
$ 特定文化特性的貨幣符號。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.
簽署sign 選擇性的正負號。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-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 members 控制項可能是但不需要出現在輸入字串中的元素。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 以括弧形式括住數值的sign元素。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)

使用指定樣式和特定文化特性格式,將數字的範圍表示轉換為其對等的 DecimalConverts 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 數字,等於包含在 s 中的數字,如同 styleprovider 所指定。The Decimal number equivalent to the number contained in s as specified by style and provider.

Parse(String, IFormatProvider)

使用指定的特定文化特性格式資訊,將數字的字串表示轉換為其對等的 DecimalConverts 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 表單的按鈕 click 事件處理常式。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. 例如,它可以用來將使用者輸入的文字轉換成 HTML 文字方塊中的數位值。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:

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 樣式來加以解讀。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:

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 的開頭,如果 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.
簽署sign 選擇性的正負號。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-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 members 控制項可能是但不需要出現在輸入字串中的元素。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 以括弧形式括住數值的sign元素。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.

s 參數會使用針對目前系統文化特性初始化的 NumberFormatInfo 物件中的格式資訊進行剖析。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)

將數字的字串表示,轉換為其相等的 DecimalConverts 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:

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

另請參閱

適用於