Decimal.Parse Decimal.Parse Decimal.Parse Decimal.Parse Method

定義

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

多載

Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) 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) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

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

Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles)

將指定樣式中數字的字串表示轉換為其相等的 DecimalConverts the string representation of a number in a specified style to its Decimal equivalent.

Parse(String) Parse(String) Parse(String) Parse(String)

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

Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) 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 String String String

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

style
NumberStyles NumberStyles NumberStyles 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 IFormatProvider 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.

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.

備註

參數會定義允許的s參數格式,讓剖析作業成功。 styleThe style parameter defines the allowable format of the s parameter for the parse operation to succeed. 它必須是NumberStyles列舉中的位旗標組合。It must be a combination of bit flags from the NumberStyles enumeration. 不支援NumberStyles下列成員:The following NumberStyles members are not supported:

視的值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]

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

元素Element 說明Description
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是CurrencyNegativePatternprovider參數的CurrencyPositivePattern GetFormat方法所傳回NumberFormatInfo之物件的和屬性所定義。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. 如果s style包含旗標,貨幣符號可能會出現在中。NumberStyles.AllowCurrencySymbolThe currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
wsws 選擇性的空白字元。Optional white space. s s style NumberStyles.AllowTrailingWhite如果包含style 旗標,空白字元可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingWhite出現在的結尾。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. s s style NumberStyles.AllowTrailingSign如果包含style 旗標,則正負號可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingSign出現在的結尾。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. 如果包含s style 旗標,則可以在中使用括弧來NumberStyles.AllowParentheses表示負數值。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. provider s如果包含NumberStyles.AllowThousands旗標,則所定義之文化特性的千位分隔符號會出現在中。 styleThe 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. provider s如果包含NumberStyles.AllowDecimalPoint旗標,則所定義之文化特性的小數點符號可能會出現在中。 styleThe 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. 只有在包含s style 旗標時,小數位數才會出現在中。NumberStyles.AllowDecimalPointFractional 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. 如果s 包含旗NumberStyles.AllowExponent標, 參數可以表示指數標記法中的數位。 styleThe 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樣式) 一律會成功剖析。A string with digits only (which corresponds to the None style) always parses successfully. 其餘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 開頭sws元素。The ws element at the beginning of s.
AllowTrailingWhite 結尾sws元素。The ws element at the end of s.
AllowLeadingSign 在開頭s的 sign 元素。The sign element at the beginning of s.
AllowTrailingSign 結尾ssign元素。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 、、、和 ws signThe ws, sign, ,, and . 要素.elements.
Any 除了以外s的所有樣式都不能代表十六進位數位。All styles, except s cannot represent a hexadecimal number.

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

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

如果在剖析作業期間于s參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號.If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

參數

傳回

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) 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 String String String

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

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

例外狀況

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物件的Parse(String, IFormatProvider) Decimal物件會傳遞至方法,以將使用者的輸入轉換成值。 NumberFormatInfoThe 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

備註

此方法的多載通常用來將可透過各種方式格式化的文字轉換Decimal成值。 Parse(String, IFormatProvider)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:

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

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

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

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.

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

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

如果在剖析作業期間于s參數中遇到分隔符號,而且適用的貨幣或十進位和群組分隔符號相同,則剖析作業會假設分隔符號是小數分隔符號,而不是群組分隔符號.If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles) 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 String String String

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

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

例外狀況

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.

備註

參數會定義s參數中允許的樣式專案(例如千位分隔符號、空白字元和貨幣符號),使剖析作業成功。 styleThe 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]

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

元素Element 說明Description
wsws 選擇性的空白字元。Optional white space. s s style NumberStyles.AllowTrailingWhite如果包含style 旗標,空白字元可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingWhite出現在的結尾。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.CurrencyNegativePattern目前文化特性的和NumberFormatInfo.CurrencyPositivePattern屬性所定義。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果s style包含旗標,則目前文化特性的貨幣符號可能會出現在中。NumberStyles.AllowCurrencySymbolThe current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. s s style NumberStyles.AllowTrailingSign如果包含style 旗標,則正負號可能會出現在開頭,而且如果包含旗標,它可以NumberStyles.AllowLeadingSign出現在的結尾。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. 如果包含s style 旗標,則可以在中使用括弧來NumberStyles.AllowParentheses表示負數值。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. 如果s style包含旗標,則目前文化特性的千位分隔符號可能會出現在中。NumberStyles.AllowThousandsThe current culture's thousands separator can appear in s if style includes the NumberStyles.AllowThousands flag.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果s style包含旗標,則目前文化特性的小數點符號可能會出現在中。NumberStyles.AllowDecimalPointThe 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. 只有在包含s style 旗標時,小數位數才會出現在中。NumberStyles.AllowDecimalPointFractional 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. 如果s 包含旗NumberStyles.AllowExponent標, 參數可以表示指數標記法中的數位。 styleThe 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樣式) 一律會成功剖析。A string with digits only (which corresponds to the None style) always parses successfully. 其餘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 開頭sws元素。The ws element at the beginning of s.
AllowTrailingWhite 結尾sws元素。The ws element at the end of s.
AllowLeadingSign 在開頭s的 sign 元素。The sign element at the beginning of s.
AllowTrailingSign 結尾ssign元素。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.

參數會使用針對目前系統文化特性初始化之NumberFormatInfo物件中的格式資訊進行剖析。 sThe 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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

Parse(String) Parse(String) Parse(String) 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 String String String

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

傳回

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

例外狀況

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]

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

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

使用樣式來解讀參數sNumberStyles.NumberParameter s is interpreted using the NumberStyles.Number style. 這表示允許使用空白字元和千位分隔符號,但是貨幣符號則不是。This means that white space and thousands separators are allowed but currency symbols are not. 若要明確定義可以出現在中s的元素(例如貨幣符號、千位分隔符號和空白字元),請使用Decimal.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. 如需分隔符號的詳細資訊, CurrencyDecimalSeparatorNumberDecimalSeparator參閱CurrencyGroupSeparator、、 NumberGroupSeparator和。For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於