Single.Parse 方法

定義

將數字的字串表示轉換為其對等單精確度浮點數。Converts the string representation of a number to its single-precision floating-point number equivalent.

多載

Parse(String, NumberStyles, IFormatProvider)

將數字的字串表示 (使用指定樣式和的特定文化特性格式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent.

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its single-precision floating-point number equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等單精確度浮點數。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent.

Parse(String)

將數字的字串表示轉換為其對等的單精確度浮點數。Converts the string representation of a number to its single-precision floating-point number equivalent.

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified style to its single-precision floating-point number equivalent.

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

Parse(String, NumberStyles, IFormatProvider)

將數字的字串表示 (使用指定樣式和的特定文化特性格式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent.

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

參數

s
String

字串,其包含要轉換的數字。A string that contains a number to convert.

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicates the style elements that can be present in s. 所要指定一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

物件,其提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

Single

單精確度浮點數,其相當於 s 中指定的數值或符號。A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不代表數字。s does not represent a numeric value.

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

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

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

範例

下列程式碼範例會使用 Parse(String, NumberStyles, IFormatProvider) 方法來剖析值的字串表示 SingleThe following code example uses the Parse(String, NumberStyles, IFormatProvider) method to parse the string representations of Single values. 陣列中的每個字串都是使用 en-us、nl NL 和自訂文化特性的格式化慣例來剖析。Each string in an array is parsed using the formatting conventions of the en-US, nl-NL, and a custom culture. 自訂文化特性會將其群組分隔符號定義為底線 ( "" ) ,並將其群組大小定義為二。The custom culture defines its group separator symbol as the underscore ("") and its group size as two.

using System;
using System.Globalization;

public class Example
{
    public static void Main()
    {
      // Define an array of string values.
      string[] values = { " 987.654E-2", " 987,654E-2",  "(98765,43210)",
                          "9,876,543.210", "9.876.543,210",  "98_76_54_32,19" };
      // Create a custom culture based on the invariant culture.
      CultureInfo ci = new CultureInfo("");
      ci.NumberFormat.NumberGroupSizes = new int[] { 2 };
      ci.NumberFormat.NumberGroupSeparator = "_";

      // Define an array of format providers.
      CultureInfo[] providers = { new CultureInfo("en-US"),
                                  new CultureInfo("nl-NL"), ci };

      // Define an array of styles.
      NumberStyles[] styles = { NumberStyles.Currency, NumberStyles.Float };

      // Iterate the array of format providers.
      foreach (CultureInfo provider in providers)
      {
         Console.WriteLine("Parsing using the {0} culture:",
                           provider.Name == String.Empty ? "Invariant" : provider.Name);
         // Parse each element in the array of string values.
         foreach (string value in values)
         {
            foreach (NumberStyles style in styles)
            {
               try {
                  float number = Single.Parse(value, style, provider);
                  Console.WriteLine("   {0} ({1}) -> {2}",
                                    value, style, number);
               }
               catch (FormatException) {
                  Console.WriteLine("   '{0}' is invalid using {1}.", value, style);
               }
               catch (OverflowException) {
                  Console.WriteLine("   '{0}' is out of the range of a Single.", value);
               }
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
// Parsing using the en-US culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the nl-NL culture:
//    ' 987.654E-2' is invalid using Currency.
//    ' 987.654E-2' is invalid using Float.
//    ' 987,654E-2' is invalid using Currency.
//     987,654E-2 (Float) -> 9.87654
//    (98765,43210) (Currency) -> -98765.43
//    '(98765,43210)' is invalid using Float.
//    '9,876,543.210' is invalid using Currency.
//    '9,876,543.210' is invalid using Float.
//    9.876.543,210 (Currency) -> 9876543
//    '9.876.543,210' is invalid using Float.
//    '98_76_54_32,19' is invalid using Currency.
//    '98_76_54_32,19' is invalid using Float.
//
// Parsing using the Invariant culture:
//    ' 987.654E-2' is invalid using Currency.
//     987.654E-2 (Float) -> 9.87654
//    ' 987,654E-2' is invalid using Currency.
//    ' 987,654E-2' is invalid using Float.
//    (98765,43210) (Currency) -> -9.876543E+09
//    '(98765,43210)' is invalid using Float.
//    9,876,543.210 (Currency) -> 9876543
//    '9,876,543.210' is invalid using Float.
//    '9.876.543,210' is invalid using Currency.
//    '9.876.543,210' is invalid using Float.
//    98_76_54_32,19 (Currency) -> 9.876543E+09
//    '98_76_54_32,19' is invalid using Float.
Imports System.Globalization

Module Example
    Public Sub Main()
      ' Define an array of string values.
      Dim values() As String = { " 987.654E-2", " 987,654E-2", _
                                 "(98765,43210)", "9,876,543.210",  _
                                 "9.876.543,210",  "98_76_54_32,19" }
      ' Create a custom culture based on the invariant culture.
      Dim ci As New CultureInfo("")
      ci.NumberFormat.NumberGroupSizes = New Integer() { 2 }
      ci.NumberFormat.NumberGroupSeparator = "_"
      
      ' Define an array of format providers.
      Dim providers() As CultureInfo = { New CultureInfo("en-US"), _
                                             New CultureInfo("nl-NL"), ci }       
      
      ' Define an array of styles.
      Dim styles() As NumberStyles = { NumberStyles.Currency, NumberStyles.Float }
      
      ' Iterate the array of format providers.
      For Each provider As CultureInfo In providers
         Console.WriteLine("Parsing using the {0} culture:", _
                           If(provider.Name = String.Empty, "Invariant", provider.Name))
         ' Parse each element in the array of string values.
         For Each value As String In values
            For Each style As NumberStyles In styles
               Try
                  Dim number As Single = Single.Parse(value, style, provider)            
                  Console.WriteLine("   {0} ({1}) -> {2}", _
                                    value, style, number)
               Catch e As FormatException
                  Console.WriteLine("   '{0}' is invalid using {1}.", value, style)            
               Catch e As OverflowException
                  Console.WriteLine("   '{0}' is out of the range of a Single.", value)
               End Try 
            Next            
         Next         
         Console.WriteLine()
      Next
   End Sub   
End Module 
' The example displays the following output:
'       Parsing using the en-US culture:
'          ' 987.654E-2' is invalid using Currency.
'           987.654E-2 (Float) -> 9.87654
'          ' 987,654E-2' is invalid using Currency.
'          ' 987,654E-2' is invalid using Float.
'          (98765,43210) (Currency) -> -9.876543E+09
'          '(98765,43210)' is invalid using Float.
'          9,876,543.210 (Currency) -> 9876543
'          '9,876,543.210' is invalid using Float.
'          '9.876.543,210' is invalid using Currency.
'          '9.876.543,210' is invalid using Float.
'          '98_76_54_32,19' is invalid using Currency.
'          '98_76_54_32,19' is invalid using Float.
'       
'       Parsing using the nl-NL culture:
'          ' 987.654E-2' is invalid using Currency.
'          ' 987.654E-2' is invalid using Float.
'          ' 987,654E-2' is invalid using Currency.
'           987,654E-2 (Float) -> 9.87654
'          (98765,43210) (Currency) -> -98765.43
'          '(98765,43210)' is invalid using Float.
'          '9,876,543.210' is invalid using Currency.
'          '9,876,543.210' is invalid using Float.
'          9.876.543,210 (Currency) -> 9876543
'          '9.876.543,210' is invalid using Float.
'          '98_76_54_32,19' is invalid using Currency.
'          '98_76_54_32,19' is invalid using Float.
'       
'       Parsing using the Invariant culture:
'          ' 987.654E-2' is invalid using Currency.
'           987.654E-2 (Float) -> 9.87654
'          ' 987,654E-2' is invalid using Currency.
'          ' 987,654E-2' is invalid using Float.
'          (98765,43210) (Currency) -> -9.876543E+09
'          '(98765,43210)' is invalid using Float.
'          9,876,543.210 (Currency) -> 9876543
'          '9,876,543.210' is invalid using Float.
'          '9.876.543,210' is invalid using Currency.
'          '9.876.543,210' is invalid using Float.
'          98_76_54_32,19 (Currency) -> 9.876543E+09
'          '98_76_54_32,19' is invalid using Float.

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

style參數會定義 (的樣式元素,例如空白字元、千位分隔符號和貨幣符號) 可 s 讓剖析作業成功的參數使用。The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. 它必須是來自列舉的位旗標組合 NumberStylesIt must be a combination of bit flags from the NumberStyles enumeration. NumberStyles不支援下列成員:The following NumberStyles members are not supported:

s參數可包含 NumberFormatInfo.PositiveInfinitySymbol 、或, NumberFormatInfo.NegativeInfinitySymbol NumberFormatInfo.NaNSymbol 用於所指定的文化特性 providerThe s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider. 視的值而定 style ,它也可以採用下列格式:Depending on the value of style, it can also take the form:

[ws][ $ ] [sign] [整數位數,]整數位數[. [小數位數]][E [sign]指數位數][ws][ws] [$] [sign][integral-digits,]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

以方括弧括住的元素 ( [和] ) 是選擇性的。Elements framed in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

元素Element 描述Description
wsws 一系列的空白字元。A series of white-space characters. 如果包含旗標,則空格開頭可能會出現空格 s style NumberStyles.AllowLeadingWhites 如果 style 包含旗標,則會出現在結尾 NumberStyles.AllowTrailingWhiteWhite 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 負號符號 ( ) 或正號符號 (+) 。A negative sign symbol (-) or a positive sign symbol (+). 如果包含旗標,符號可以出現在的開頭, s style NumberStyles.AllowLeadingSign s 如果包含旗標,則會出現在結尾 style NumberStyles.AllowTrailingSignThe 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.AllowParenthesesParentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
整數位數integral-digits 範圍從0到9的一系列數位,可指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 如果字串包含 小數位數 元素,則 整數位數 元素可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
,, 文化特性特定的群組分隔符號。A culture-specific group separator. s如果 style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符號號可以出現在中。The current culture's group separator symbol 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-digits 範圍從0到9的一系列數位,可指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. s如果包含旗標,則小數位數可以出現在中 style NumberStyles.AllowDecimalPointFractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字元,表示值以指數 (科學) 標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. s如果包含旗標,則參數可以表示指數標記法中的數位 style NumberStyles.AllowExponentThe s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
指數位數exponential-digits 一系列的數位,範圍介於0到9之間,可指定指數。A series of digits ranging from 0 to 9 that specify an exponent.

注意

s無論引數的值為何,剖析作業都會忽略中的任何終止 NUL (U + 0000) 字元 styleAny terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

僅限數位 (的字串,其會對應至 NumberStyles.None 樣式) 如果是在類型的範圍內,則一律會成功剖析 SingleA string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Single type. 其餘的 System.Globalization.NumberStyles 成員會控制可能存在但不一定要存在於輸入字串中的元素。The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. 下表指出個別 NumberStyles 旗標如何影響可能存在的元素 sThe following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles 值NumberStyles value s除了數位之外,還允許的元素Elements permitted in s in addition to digits
None 僅限 整數位數 元素。The integral-digits element only.
AllowDecimalPoint 小數點 () 和 小數數位**元素。The decimal point (.) and fractional-digits elements.
AllowExponent "E" 或 "E" 字元,表示指數標記法。The "e" or "E" character, which indicates exponential notation. 此旗標本身支援 數位 E 位數 的值;需要額外的旗標,才能成功地將包含這類元素的字串剖析為正面或負號和小數點符號。This flag by itself supports values in the form digits E digits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite 開頭的 ws 元素 sThe ws element at the beginning of s.
AllowTrailingWhite 結尾的 ws 元素 sThe ws element at the end of s.
AllowLeadingSign 開頭的 sign 元素 sThe sign element at the beginning of s.
AllowTrailingSign 結尾的 sign 元素 sThe sign element at the end of s.
AllowParentheses 以括弧括住數值的 符號 元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符號 (,) 元素。The thousands separator (,) element.
AllowCurrencySymbol Currency ($) 元素。The currency ($) element.
Currency 所有元素。All elements. 但是, s 不能以指數標記法表示十六進位數位或數位。However, s cannot represent a hexadecimal number or a number in exponential notation.
Float 在開頭或結尾的 ws 元素 s符號 開頭 s ,以及小數點 (. ) 符號。The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. s參數也可以使用指數標記法。The s parameter can also use exponential notation.
Number wssign 、千位分隔符號 (、) 和小數點 ( ) 元素。The ws, sign, thousands separator (,) and decimal point (.) elements.
Any 所有元素。All elements. 但是, s 不能代表十六進位數位。However, s cannot represent a hexadecimal number.

provider參數是實作為 IFormatProviderThe provider parameter is an IFormatProvider implementation. 它的 GetFormat 方法 NumberFormatInfo 會傳回物件,該物件會提供有關格式的特定文化特性資訊 valueIts GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. 一般而言, provider 可以是下列其中一項:Typically, provider can be any one of the following:

如果 providernull ,則 NumberFormatInfo 會使用目前文化特性的物件。If provider is null, the NumberFormatInfo object for the current culture is used.

如果 s 超出 Single 資料類型的範圍,方法會 OverflowException 在 .NET Framework 上擲回,並在 .net Core 2.2 及更早版本上擲回。If s is out of range of the Single data type, the method throws an OverflowException on .NET Framework and .NET Core 2.2 and earlier versions. 在 .NET Core 3.0 和更新版本上, Single.NegativeInfinity 如果 s 小於 Single.MinValueSingle.PositiveInfinity 大於, s Single.MaxValue 則會傳回。On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s is less than Single.MinValue and Single.PositiveInfinity if s is greater than Single.MaxValue.

如果在剖析作業期間于參數中遇到分隔符號 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. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparator 、、 NumberDecimalSeparator CurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its single-precision floating-point number equivalent.

public:
 static float Parse(System::String ^ s, IFormatProvider ^ provider);
public static float Parse (string s, IFormatProvider provider);
public static float Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> single
Public Shared Function Parse (s As String, provider As IFormatProvider) As Single

參數

s
String

字串,其包含要轉換的數字。A string that contains a number to convert.

provider
IFormatProvider

物件,提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

Single

單精確度浮點數,其相當於 s 中指定的數值或符號。A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是有效格式的數字。s does not represent a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: 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. NumberFormatInfo然後,會將屬於該 CultureInfo 物件的物件傳遞至 Parse(String, IFormatProvider) 方法,以將使用者的輸入轉換成 Single 值。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 Single value.

protected void OkToSingle_Click(object sender, EventArgs e)
{
   string locale;
   float 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 = Single.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 OkToSingle_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToSingle.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Single

   ' 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 = Single.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As OverflowException
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

這個多載通常用來轉換可以各種方式格式化為值的文字 SingleThis overload is typically used to convert text that can be formatted in a variety of ways to a Single 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參數是使用 NumberStyles.Float 和旗標的組合來解讀 NumberStyles.AllowThousandsThe s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. s參數可以包含 NumberFormatInfo.PositiveInfinitySymbol NumberFormatInfo.NegativeInfinitySymbol 或所指定之文化特性的、或, NumberFormatInfo.NaNSymbol provider 也可以包含格式的字串:The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider, or it can contain a string of the form:

[ws][sign]整數位數[.[小數位 數]][E [sign]指數位數][ws][ws][sign]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

選擇性元素會以方括弧括住, ( [和] ) 。Optional elements are framed in square brackets ([ and ]). 包含「位數」一詞的元素包含一連串數位字元,範圍從0到9。Elements that contain the term "digits" consist of a series of numeric characters ranging from 0 to 9.

元素Element 描述Description
wsws 一系列的空白字元。A series of white-space characters.
簽署sign 負號符號 ( ) 或正號符號 (+) 。A negative sign symbol (-) or a positive sign symbol (+).
整數位數integral-digits 範圍從0到9的一系列數位,可指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 整數位數 的執行可以依群組分隔符號號進行分割。Runs of integral-digits can be partitioned by a group-separator symbol. 例如,在某些文化特性中,逗號 (,) 區隔數以千計的群組。For example, in some cultures a comma (,) separates groups of thousands. 如果字串包含 小數位數 元素,則 整數位數 元素可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數位數fractional-digits 範圍從0到9的一系列數位,可指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number.
EE "E" 或 "E" 字元,表示值以指數 (科學) 標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
指數位數exponential-digits 一系列的數位,範圍介於0到9之間,可指定指數。A series of digits ranging from 0 to 9 that specify an exponent.

如需數值格式的詳細資訊,請參閱 格式化類型 主題。For more information about numeric formats, see the Formatting Types topic.

provider參數是一種 IFormatProvider 實作為方法,其方法會傳回 GetFormat NumberFormatInfo 提供特定文化特性格式資訊的物件。The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information. 叫用 Parse(String, IFormatProvider) 方法時,它會呼叫 provider 參數的 GetFormat 方法,並將代表型別的物件傳遞給它 Type NumberFormatInfoWhen the Parse(String, IFormatProvider) method is invoked, it calls the provider parameter's GetFormat method and passes it a Type object that represents the NumberFormatInfo type. GetFormat方法接著 NumberFormatInfo 會傳回提供參數格式相關資訊的物件 sThe GetFormat method then returns the NumberFormatInfo object that provides information about the format of the s parameter. 有三種方式可使用 provider 參數提供自訂格式資訊給剖析作業:There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

  • 您可以傳遞 CultureInfo 代表提供格式資訊之文化特性的物件。You can pass a CultureInfo object that represents the culture that supplies formatting information. GetFormat 的方法 NumberFormatInfo 會傳回物件,該物件會提供該文化特性的數值格式資訊。Its GetFormat method returns the NumberFormatInfo object that provides numeric formatting information for that culture.

  • 您可以傳遞 NumberFormatInfo 提供數值格式資訊的實際物件。You can pass the actual NumberFormatInfo object that provides numeric formatting information. (的實執行 GetFormat 只會傳回本身。 ) (Its implementation of GetFormat just returns itself.)

  • 您可以傳遞可執行檔自訂物件 IFormatProviderYou can pass a custom object that implements IFormatProvider. 它的方法具現 GetFormat 化,並傳回 NumberFormatInfo 提供格式資訊的物件。Its GetFormat method instantiates and returns the NumberFormatInfo object that provides formatting information.

如果 provider null NumberFormatInfo 無法取得,則會使用目前系統文化特性的格式資訊。If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

如果 s 超出 Single 資料類型的範圍,方法會 OverflowException 在 .NET Framework 上擲回,並在 .net Core 2.2 及更早版本上擲回。If s is out of range of the Single data type, the method throws an OverflowException on .NET Framework and .NET Core 2.2 and earlier versions. 在 .NET Core 3.0 和更新版本上, Single.NegativeInfinity 如果 s 小於 Single.MinValueSingle.PositiveInfinity 大於, s Single.MaxValue 則會傳回。On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s is less than Single.MinValue and Single.PositiveInfinity if s is greater than Single.MaxValue.

如果在剖析作業期間于參數中遇到分隔符號 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. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparator 、、 NumberDecimalSeparator CurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

的一些範例 s 是 "100"、"-123456789"、"123.45 e + 6"、"+ 500"、"5e2"、"3.1416"、"600"、"-. 123" 和 "-無限大"。Some examples of s are "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123", and "-Infinity".

另請參閱

適用於

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等單精確度浮點數。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent.

public static float Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowTrailingWhite | System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
public static float Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowTrailingWhite | System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> single
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent | System.Globalization.NumberStyles.AllowLeadingSign | System.Globalization.NumberStyles.AllowLeadingWhite | System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowTrailingWhite | System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Single

參數

s
ReadOnlySpan<Char>

字元範圍,其包含要轉換的數字。A character span that contains the number to convert.

style
NumberStyles

列舉值的位元組合,其表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicate the style elements that can be present in s. 所要指定一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

物件,其提供關於 s 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about s.

傳回

Single

單精確度浮點數,其相當於 s 中指定的數值或符號。A single-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

s 不代表數字。s does not represent a numeric value.

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

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

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

如果超出 s Single 資料類型的範圍,方法會在 Single.NegativeInfinity s 小於 Single.MinValueSingle.PositiveInfinity s 大於 Single.MaxValue 時傳回。If s is out of range of the Single data type, the method returns Single.NegativeInfinity if s is less than Single.MinValue and Single.PositiveInfinity if s is greater than Single.MaxValue.

適用於

Parse(String)

將數字的字串表示轉換為其對等的單精確度浮點數。Converts the string representation of a number to its single-precision floating-point number equivalent.

public:
 static float Parse(System::String ^ s);
public static float Parse (string s);
static member Parse : string -> single
Public Shared Function Parse (s As String) As Single

參數

s
String

字串,其包含要轉換的數字。A string that contains a number to convert.

傳回

Single

單精確度浮點數,其相當於 s 中指定的數值或符號。A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是有效格式的數字。s does not represent a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number less than MinValue or greater than MaxValue.

範例

下列範例會使用 Parse(String) 方法,將字串陣列轉換為相等的 Single 值。The following example uses the Parse(String) method to convert an array of strings to equivalent Single values.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { "100", "(100)", "-123,456,789", "123.45e+6", 
                          "+500", "5e2", "3.1416", "600.", "-.123", 
                          "-Infinity", "-1E-16", Double.MaxValue.ToString(), 
                          Single.MinValue.ToString(), String.Empty };
      foreach (string value in values)
      {
         try {   
            float number = Single.Parse(value);
            Console.WriteLine("{0} -> {1}", value, number);
         }
         catch (FormatException) {
            Console.WriteLine("'{0}' is not in a valid format.", value);
         }
         catch (OverflowException) {
            Console.WriteLine("{0} is outside the range of a Single.", value);
         }
      }                                  
   }
}
// The example displays the following output:
//       100 -> 100
//       '(100)' is not in a valid format.
//       -123,456,789 -> -1.234568E+08
//       123.45e+6 -> 1.2345E+08
//       +500 -> 500
//       5e2 -> 500
//       3.1416 -> 3.1416
//       600. -> 600
//       -.123 -> -0.123
//       -Infinity -> -Infinity
//       -1E-16 -> -1E-16
//       1.79769313486232E+308 is outside the range of a Single.
//       -3.402823E+38 -> -3.402823E+38
//       '' is not in a valid format.
Module Example
   Public Sub Main()
      Dim values() As String = { "100", "(100)", "-123,456,789", "123.45e+6", _
                                 "+500", "5e2", "3.1416", "600.", "-.123", _
                                 "-Infinity", "-1E-16", Double.MaxValue.ToString(), _
                                 Single.MinValue.ToString(), String.Empty }
      For Each value As String In values
         Try   
            Dim number As Single = Single.Parse(value)
            Console.WriteLine("{0} -> {1}", value, number)
         Catch e As FormatException
            Console.WriteLine("'{0}' is not in a valid format.", value)
         Catch e As OverflowException
            Console.WriteLine("{0} is outside the range of a Single.", value)
         End Try
      Next                                  
   End Sub
End Module
' The example displays the following output:
'       100 -> 100
'       '(100)' is not in a valid format.
'       -123,456,789 -> -1.234568E+08
'       123.45e+6 -> 1.2345E+08
'       +500 -> 500
'       5e2 -> 500
'       3.1416 -> 3.1416
'       600. -> 600
'       -.123 -> -0.123
'       -Infinity -> -Infinity
'       -1E-16 -> -1E-16
'       1.79769313486232E+308 is outside the range of a Single.
'       -3.402823E+38 -> -3.402823E+38
'       '' is not in a valid format.

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

s參數可以包含目前文化特性的 PositiveInfinitySymbolNegativeInfinitySymbolNaNSymbol 或格式的字串:The s parameter can contain the current culture's PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol, or a string of the form:

[ws][sign][整數位數[]]整數位數[.[小數位 數]][e [sign]指數位數][ws][ws][sign] [integral-digits[,]]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws]

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

元素Element 描述Description
wsws 一系列的空白字元。A series of white space characters.
簽署sign 負號符號或正號符號。A negative sign symbol or a positive sign symbol. 有效的正負號字元是由 NumberFormatInfo.NegativeSign NumberFormatInfo.PositiveSign 目前文化特性的和屬性所決定。Valid sign characters are determined by the NumberFormatInfo.NegativeSign and NumberFormatInfo.PositiveSign properties of the current culture. 只能使用前置正負號。Only a leading sign can be used.
整數位數integral-digits 範圍從0到9的一系列數位,可指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 整數位數 的執行可以依群組分隔符號號進行分割。Runs of integral-digits can be partitioned by a group-separator symbol. 例如,在某些文化特性中,逗號 (,) 區隔數以千計的群組。For example, in some cultures a comma (,) separates groups of thousands. 如果字串包含 小數位數 元素,則 整數位數 元素可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.
,, 特定文化特性的千位分隔符號。A culture-specific thousands separator symbol.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol.
小數位數fractional-digits 範圍從0到9的一系列數位,可指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number.
EE "E" 或 "E" 字元,表示值以指數 (科學) 標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
指數位數exponential-digits 一系列的數位,範圍介於0到9之間,可指定指數。A series of digits ranging from 0 to 9 that specify an exponent.

s參數是使用 NumberStyles.Float 和旗標的組合來解讀 NumberStyles.AllowThousandsThe s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. 這表示允許空白字元和千位分隔符號,但不允許使用貨幣符號。This means that white space and thousands separators are allowed but currency symbols are not. 若要明確定義 (的元素,例如可以存在的貨幣符號、千位分隔符號和空白字元) s ,請使用方法多載 Parse(String, NumberStyles)To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use the Parse(String, NumberStyles) method overload.

您可以 s 使用 NumberFormatInfo 針對目前系統文化特性初始化之物件中的格式資訊,來剖析參數。The s parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 如需詳細資訊,請參閱CurrentInfoFor more information, see CurrentInfo. 若要使用特定文化特性的格式資訊來剖析字串,請使用 Parse(String, IFormatProvider)Parse(String, NumberStyles, IFormatProvider) 方法。To parse a string by using the formatting information of a specific culture, use the Parse(String, IFormatProvider) or Parse(String, NumberStyles, IFormatProvider) method.

一般來說,如果您將 Parse 呼叫方法所建立的字串傳遞給方法 ToString ,則 Single 會傳回原始值。Ordinarily, if you pass the Parse method a string that is created by calling the ToString method, the original Single value is returned. 不過,因為精確度遺失,所以值可能不相等。However, because of a loss of precision, the values may not be equal.

如果 s 超出 Single 資料類型的範圍,方法會 OverflowException 在 .NET Framework 上擲回,並在 .net Core 2.2 及更早版本上擲回。If s is out of range of the Single data type, the method throws an OverflowException on .NET Framework and .NET Core 2.2 and earlier versions. 在 .NET Core 3.0 和更新版本上, Single.NegativeInfinity 如果 s 小於 Single.MinValueSingle.PositiveInfinity 大於, s Single.MaxValue 則會傳回。On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s is less than Single.MinValue and Single.PositiveInfinity if s is greater than Single.MaxValue.

如果在剖析作業期間于參數中遇到分隔符號 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. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparator 、、 NumberDecimalSeparator CurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其對等單精確度浮點數。Converts the string representation of a number in a specified style to its single-precision floating-point number equivalent.

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

參數

s
String

字串,其包含要轉換的數字。A string that contains a number to convert.

style
NumberStyles

列舉值的位元組合,表示 s 中可以存在的樣式項目。A bitwise combination of enumeration values that indicates the style elements that can be present in s. 所要指定一般值為 FloatAllowThousands 的組合。A typical value to specify is Float combined with AllowThousands.

傳回

Single

單精確度浮點數,其相當於 s 中指定的數值或符號。A single-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

例外狀況

snulls is null.

s 不是有效格式的數字。s is not a number in a valid format.

僅限於 .NET Framework 與 .NET Core 2.2 和更早版本:s 代表小於 MinValue 或大於 MaxValue 的數字。.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue.

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

-或--or- style 包含 AllowHexSpecifier 值。style includes the AllowHexSpecifier value.

範例

下列範例會使用 Parse(String, NumberStyles) 方法來剖析值的字串表示 SingleThe following example uses the Parse(String, NumberStyles) method to parse the string representations of Single values. 此範例使用 en-us 文化特性的格式資訊。The example uses formatting information for the en-US culture.

using System;
using System.Globalization;
using System.Threading;

public class ParseString
{
   public static void Main()
   {
      // Set current thread culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      
      string value;
      NumberStyles styles;
      
      // Parse a string in exponential notation with only the AllowExponent flag. 
      value = "-1.063E-02";
      styles = NumberStyles.AllowExponent;
      ShowNumericValue(value, styles);
      
      // Parse a string in exponential notation
      // with the AllowExponent and Number flags.
      styles = NumberStyles.AllowExponent | NumberStyles.Number;
      ShowNumericValue(value, styles);

      // Parse a currency value with leading and trailing white space, and
      // white space after the U.S. currency symbol.
      value = " $ 6,164.3299  ";
      styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
      ShowNumericValue(value, styles);
      
      // Parse negative value with thousands separator and decimal.
      value = "(4,320.64)";
      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float; 
      ShowNumericValue(value, styles);
      
      styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float | NumberStyles.AllowThousands;
      ShowNumericValue(value, styles);
   }

   private static void ShowNumericValue(string value, NumberStyles styles)
   {
      Single number;
      try
      {
         number = Single.Parse(value, styles);
         Console.WriteLine("Converted '{0}' using {1} to {2}.", 
                           value, styles.ToString(), number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to parse '{0}' with styles {1}.", 
                           value, styles.ToString());
      }
      Console.WriteLine();                           
   }   
}
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//    
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//    
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//    
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//    
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Imports System.Globalization
Imports System.Threading

Module ParseStrings
   Public Sub Main()
      ' Set current thread culture to en-US.
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
            
      Dim value As String
      Dim styles As NumberStyles
      
      ' Parse a string in exponential notation with only the AllowExponent flag. 
      value = "-1.063E-02"
      styles = NumberStyles.AllowExponent
      ShowNumericValue(value, styles) 
      
      ' Parse a string in exponential notation
      ' with the AllowExponent and Number flags.
      styles = NumberStyles.AllowExponent Or NumberStyles.Number
      ShowNumericValue(value, styles)

      ' Parse a currency value with leading and trailing white space, and
      ' white space after the U.S. currency symbol.
      value = " $ 6,164.3299  "
      styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
      ShowNumericValue(value, styles)
      
      ' Parse negative value with thousands separator and decimal.
      value = "(4,320.64)"
      styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
               Or NumberStyles.Float 
      ShowNumericValue(value, styles)
      
      styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
               Or NumberStyles.Float Or NumberStyles.AllowThousands
      ShowNumericValue(value, styles)
   End Sub
   
   Private Sub ShowNumericValue(value As String, styles As NumberStyles)
      Dim number As Single
      Try
         number = Single.Parse(value, styles)
         Console.WriteLine("Converted '{0}' using {1} to {2}.", _
                           value, styles.ToString(), number)
      Catch e As FormatException
         Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
                           value, styles.ToString())
      End Try
      Console.WriteLine()                           
   End Sub
End Module
' The example displays the following output to the console:
'    Unable to parse '-1.063E-02' with styles AllowExponent.
'    
'    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'    
'    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
'    
'    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'    
'    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.

備註

在 .NET Core 3.0 和更新版本中,太大而無法表示的值會四捨五入至 PositiveInfinity NegativeInfinity IEEE 754 規格所需的或。In .NET Core 3.0 and later, values that are too large to represent are rounded to PositiveInfinity or NegativeInfinity as required by the IEEE 754 specification. 在先前的版本中(包括 .NET Framework),剖析太大而無法表示的值會導致失敗。In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

style參數會定義 (的樣式元素,例如空白字元、千位分隔符號和貨幣符號) 可 s 讓剖析作業成功的參數使用。The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. 它必須是來自列舉的位旗標組合 NumberStylesIt must be a combination of bit flags from the NumberStyles enumeration. NumberStyles不支援下列成員:The following NumberStyles members are not supported:

s參數可以包含目前文化特性的 PositiveInfinitySymbolNegativeInfinitySymbolNaNSymbolThe s parameter can contain the current culture's PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol. 視的值而定 style ,它也可以採用下列格式:Depending on the value of style, it can also take the form:

[ws][ $ ] [sign] [整數 位數 []]整數位數[.[小數位 數]][E [sign]指數位數][ws][ws][$][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

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

wsws
一系列的空白字元。A series of white-space characters. 如果包含旗標,則空格開頭可能會出現空格 s style NumberStyles.AllowLeadingWhites 如果 style 包含旗標,則會出現在結尾 NumberStyles.AllowTrailingWhiteWhite 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
負號符號 ( ) 或正號符號 (+) 。A negative sign symbol (-) or a positive sign symbol (+). 如果包含旗標,符號可以出現在的開頭, s style NumberStyles.AllowLeadingSign s 如果包含旗標,則會出現在結尾 style NumberStyles.AllowTrailingSignThe 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.AllowParenthesesParentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.

整數位數integral-digits
範圍從0到9的一系列數位,可指定數位的整數部分。A series of digits ranging from 0 to 9 that specify the integral part of the number. 如果字串包含 小數位數 元素,則 整數位數 元素可能不存在。The integral-digits element can be absent if the string contains the fractional-digits element.

,,
文化特性特定的群組分隔符號。A culture-specific group separator. s如果 style 包含 NumberStyles.AllowThousands 旗標,則目前文化特性的群組分隔符號號可以出現在中。The current culture's group separator symbol 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-digits
範圍從0到9的一系列數位,可指定數位的小數部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. s如果包含旗標,則小數位數可以出現在中 style NumberStyles.AllowDecimalPointFractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

EE
"E" 或 "E" 字元,表示值以指數 (科學) 標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. value如果包含旗標,則參數可以表示指數標記法中的數位 style NumberStyles.AllowExponentThe value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

指數位數exponential-digits
一系列的數位,範圍介於0到9之間,可指定指數。A series of digits ranging from 0 to 9 that specify an exponent.

注意

s無論引數的值為何,剖析作業都會忽略中的任何終止 NUL (U + 0000) 字元 styleAny terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

僅限數位 (的字串,其會對應至 NumberStyles.None 樣式) 如果是在類型的範圍內,則一律會成功剖析 SingleA string with digits only (which corresponds to the NumberStyles.None style) always parses successfully if it is in the range of the Single type. 其餘的 System.Globalization.NumberStyles 成員會控制可能存在但不一定要存在於輸入字串中的元素。The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. 下表指出個別 NumberStyles 旗標如何影響可能存在的元素 sThe following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles 值NumberStyles value s除了數位之外,還允許的元素Elements permitted in s in addition to digits
None 僅限 整數位數 元素。The integral-digits element only.
AllowDecimalPoint 小數點 () 和 小數數位**元素。The decimal point (.) and fractional-digits elements.
AllowExponent "E" 或 "E" 字元,表示指數標記法。The "e" or "E" character, which indicates exponential notation. 此旗標本身支援 數位 E 位數 的值;需要額外的旗標,才能成功地將包含這類元素的字串剖析為正面或負號和小數點符號。This flag by itself supports values in the form digits E digits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite 開頭的 ws 元素 sThe ws element at the beginning of s.
AllowTrailingWhite 結尾的 ws 元素 sThe ws element at the end of s.
AllowLeadingSign 開頭的 sign 元素 sThe sign element at the beginning of s.
AllowTrailingSign 結尾的 sign 元素 sThe sign element at the end of s.
AllowParentheses 以括弧括住數值的 符號 元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符號 (,) 元素。The thousands separator (,) element.
AllowCurrencySymbol Currency ($) 元素。The currency ($) element.
Currency 所有元素。All elements. 但是, s 不能以指數標記法表示十六進位數位或數位。However, s cannot represent a hexadecimal number or a number in exponential notation.
Float 在開頭或結尾的 ws 元素 s符號 開頭 s ,以及小數點 (. ) 符號。The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. s參數也可以使用指數標記法。The s parameter can also use exponential notation.
Number wssign 、千位分隔符號 (、) 和小數點 ( ) 元素。The ws, sign, thousands separator (,) and decimal point (.) elements.
Any 所有元素。All elements. 但是, s 不能代表十六進位數位。However, s cannot represent a hexadecimal number.

的一些範例 s 是 "100"、"-123456789"、"123.45 e + 6"、"+ 500"、"5e2"、"3.1416"、"600"、"-. 123" 和 "-無限大"。Some examples of s are "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123", and "-Infinity".

s參數會使用 NumberFormatInfo 針對目前系統文化特性初始化之物件中的格式資訊進行剖析。The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. 若要指定用於剖析作業之格式化資訊的文化特性,請呼叫多載 Parse(String, NumberStyles, IFormatProvider)To specify the culture whose formatting information is used for the parse operation, call the Parse(String, NumberStyles, IFormatProvider) overload.

一般來說,如果您將 Parse 呼叫方法所建立的字串傳遞給方法 ToString ,則 Single 會傳回原始值。Ordinarily, if you pass the Parse method a string that is created by calling the ToString method, the original Single value is returned. 不過,因為精確度遺失,所以值可能不相等。However, because of a loss of precision, the values may not be equal.

如果 s 超出 Single 資料類型的範圍,方法會 OverflowException 在 .NET Framework 上擲回,並在 .net Core 2.2 及更早版本上擲回。If s is out of range of the Single data type, the method throws an OverflowException on .NET Framework and .NET Core 2.2 and earlier versions. 在 .NET Core 3.0 和更新版本上, Single.NegativeInfinity 如果 s 小於 Single.MinValueSingle.PositiveInfinity 大於, s Single.MaxValue 則會傳回。On .NET Core 3.0 and later versions, it returns Single.NegativeInfinity if s is less than Single.MinValue and Single.PositiveInfinity if s is greater than Single.MaxValue.

如果在剖析作業期間于參數中遇到分隔符號 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. 如需分隔符號的詳細資訊,請參閱 CurrencyDecimalSeparator 、、 NumberDecimalSeparator CurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另請參閱

適用於