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.

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

返回

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) 方法来分析 Single 值的字符串表示形式。The 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. 自定义区域性将其组分隔符符号定义为下划线(""),其组大小为2。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:
//       The format of // 987.654E-2// is invalid.
//       The format of // 987,654E-2// is invalid.
//       (98765,43210) (Currency) -> -9.876543E+09
//       9,876,543.210 (Currency) -> 9876543
//       The format of '9.876.543,210// is invalid.
//       The format of '98_76_54_32,19// is invalid.
//       
//       Parsing using the nl-NL culture:
//       The format of // 987.654E-2// is invalid.
//       The format of // 987,654E-2// is invalid.
//       (98765,43210) (Currency) -> -98765.43
//       The format of '9,876,543.210// is invalid.
//       9.876.543,210 (Currency) -> 9876543
//       The format of '98_76_54_32,19// is invalid.
//       
//       Parsing using the Invariant culture:
//       The format of // 987.654E-2// is invalid.
//       The format of // 987,654E-2// is invalid.
//       (98765,43210) (Currency) -> -9.876543E+09
//       9,876,543.210 (Currency) -> 9876543
//       The format of '9.876.543,210// is invalid.
//       98_76_54_32,19 (Currency) -> 9.876543E+09
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.

注解

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. 它必须是 NumberStyles 枚举中的位标志的组合。It must be a combination of bit flags from the NumberStyles enumeration. 以下 NumberStyles 成员不受支持:The following NumberStyles members are not supported:

s 参数可以包含 provider指定的区域性的 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbolThe 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. 如果 style 包含 NumberStyles.AllowLeadingWhite 标志,则空格可以出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingWhite 标志,则它可以出现在 s 的末尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ 区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由当前区域性的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果 style 包含 NumberStyles.AllowCurrencySymbol 标志,当前区域性的货币符号可以出现在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
signsign 负号符号(-)或正号符号(+)。A negative sign symbol (-) or a positive sign symbol (+). 如果 style 包含 NumberStyles.AllowLeadingSign 标志,则符号会出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingSign 标志,则它可以出现在 s 的末尾处。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 标志,则可以在 s 中使用括号来表示负值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digitsintegral-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. 如果 style 包含 NumberStyles.AllowThousands 标志,则当前区域性的组分隔符符号可能出现在 sThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
. 区域性特定的小数点符号。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 标志,当前区域性的小数点符号会出现在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsfractional-digits 一系列从0到9之间的数字,用于指定数字的小数部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果 style 包含 NumberStyles.AllowDecimalPoint 标志,则小数位会出现在 s 中。Fractional 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. 如果 style 包含 NumberStyles.AllowExponent 标志,则 s 参数可以表示指数表示法中的数字。The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digitsexponential-digits 一系列从0到9之间的数字,用于指定指数。A series of digits ranging from 0 to 9 that specify an exponent.

备注

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

只有数字(对应于 NumberStyles.None 样式)的字符串在 Single 类型的范围内时才会成功进行分析。A 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 标志如何影响可能出现在 s中的元素。The 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 digitsEdigits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite s开头的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s末尾的ws元素。The ws element at the end of s.
AllowLeadingSign s开头的sign元素。The sign element at the beginning of s.
AllowTrailingSign s末尾的sign元素。The sign element at the end of s.
AllowParentheses 用括号括起数值的符号元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符(,)元素。The thousands separator (,) element.
AllowCurrencySymbol 货币符号($)。The currency ($) element.
Currency 所有元素。All elements. 但是,s 不能表示十六进制数或以指数表示法表示的数字。However, s 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 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 参数是一个 IFormatProvider 实现。The provider parameter is an IFormatProvider implementation. 它的 GetFormat 方法返回一个 NumberFormatInfo 对象,该对象提供有关 value格式的区域性特定信息。Its 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:

如果 null``provider,则使用当前区域性的 NumberFormatInfo 对象。If provider is null, the NumberFormatInfo object for the current culture is used.

如果 s 超出 Single 数据类型的范围,则该方法将引发 .NET Framework 和 .NET Core 2.2 及更早版本上的 OverflowExceptionIf 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 及更高版本中,如果 s 小于 Single.MinValueSingle.PositiveInfinity s 大于 Single.MaxValue,则返回 Single.NegativeInfinityOn .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. 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor 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);
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.

返回

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

注解

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

s 参数使用 NumberStyles.FloatNumberStyles.AllowThousands 标志的组合来进行解释。The s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. s 参数可以包含 provider指定的区域性 NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol,也可以包含以下形式的字符串: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]integral-digits[.[fractional-digits]][E[sign]exponential-digits][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.
signsign 负号符号(-)或正号符号(+)。A negative sign symbol (-) or a positive sign symbol (+).
integral-digitsintegral-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-digitsfractional-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-digitsexponential-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 方法,并向其传递一个表示 NumberFormatInfo 类型的 Type 对象。When 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 对象,该对象提供有关 s 参数格式的信息。The 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.)

  • 可以传递实现 IFormatProvider的自定义对象。You 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 数据类型的范围,则该方法将引发 .NET Framework 和 .NET Core 2.2 及更早版本上的 OverflowExceptionIf 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 及更高版本中,如果 s 小于 Single.MinValueSingle.PositiveInfinity s 大于 Single.MaxValue,则返回 Single.NegativeInfinityOn .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. 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor 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 = null);
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 = null) 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.

返回

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

注解

如果 s 超出了 Single 数据类型的范围,则当 s 小于 Single.MinValue 并且 Single.PositiveInfinity 大于 s 时,该方法返回 Single.NegativeInfinitySingle.MaxValueIf 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.

返回

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.

注解

s 参数可以包含当前区域性的 PositiveInfinitySymbolNegativeInfinitySymbolNaNSymbol或格式的字符串:The s parameter can contain the current culture's PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol, or a string of the form:

[ws][sign] [integral-digits[,]]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws][ws][sign] [integral-digits[,]]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws]

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

元素Element 说明Description
wsws 一系列空白字符。A series of white space characters.
signsign 负号符号或正号符号。A negative sign symbol or a positive sign symbol. 有效的符号字符由当前区域性的 NumberFormatInfo.NegativeSignNumberFormatInfo.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-digitsintegral-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-digitsfractional-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-digitsexponential-digits 一系列从0到9之间的数字,用于指定指数。A series of digits ranging from 0 to 9 that specify an exponent.

s 参数使用 NumberStyles.FloatNumberStyles.AllowThousands 标志的组合来进行解释。The 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 数据类型的范围,则该方法将引发 .NET Framework 和 .NET Core 2.2 及更早版本上的 OverflowExceptionIf 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 及更高版本中,如果 s 小于 Single.MinValueSingle.PositiveInfinity s 大于 Single.MaxValue,则返回 Single.NegativeInfinityOn .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. 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor 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.

返回

与在 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) 方法来分析 Single 值的字符串表示形式。The 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.   

注解

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. 它必须是 NumberStyles 枚举中的位标志的组合。It 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]

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

wsws
一系列空白字符。A series of white-space characters. 如果 style 包含 NumberStyles.AllowLeadingWhite 标志,则空格可以出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingWhite 标志,则它可以出现在 s 的末尾。White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.

$
区域性特定的货币符号。A culture-specific currency symbol. 其在字符串中的位置由当前区域性的 NumberFormatInfo.CurrencyNegativePatternNumberFormatInfo.CurrencyPositivePattern 属性定义。Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. 如果 style 包含 NumberStyles.AllowCurrencySymbol 标志,当前区域性的货币符号可以出现在 s 中。The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.

signsign
负号符号(-)或正号符号(+)。A negative sign symbol (-) or a positive sign symbol (+). 如果 style 包含 NumberStyles.AllowLeadingSign 标志,则符号会出现在 s 的开头,如果 style 包含 NumberStyles.AllowTrailingSign 标志,则它可以出现在 s 的末尾处。The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 标志,则可以在 s 中使用括号来表示负值。Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.

integral-digitsintegral-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. 如果 style 包含 NumberStyles.AllowThousands 标志,则当前区域性的组分隔符符号可能出现在 sThe current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag

.
区域性特定的小数点符号。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 标志,当前区域性的小数点符号会出现在 s 中。The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

fractional-digitsfractional-digits
一系列从0到9之间的数字,用于指定数字的小数部分。A series of digits ranging from 0 to 9 that specify the fractional part of the number. 如果 style 包含 NumberStyles.AllowDecimalPoint 标志,则小数位会出现在 s 中。Fractional 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. 如果 style 包含 NumberStyles.AllowExponent 标志,则 value 参数可以表示指数表示法中的数字。The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

exponential-digitsexponential-digits
一系列从0到9之间的数字,用于指定指数。A series of digits ranging from 0 to 9 that specify an exponent.

备注

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

只有数字(对应于 NumberStyles.None 样式)的字符串在 Single 类型的范围内时才会成功进行分析。A 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 标志如何影响可能出现在 s中的元素。The 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 digitsEdigits; additional flags are needed to successfully parse strings with such elements as positive or negative signs and decimal point symbols.
AllowLeadingWhite s开头的ws元素。The ws element at the beginning of s.
AllowTrailingWhite s末尾的ws元素。The ws element at the end of s.
AllowLeadingSign s开头的sign元素。The sign element at the beginning of s.
AllowTrailingSign s末尾的sign元素。The sign element at the end of s.
AllowParentheses 用括号括起数值的符号元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 千位分隔符(,)元素。The thousands separator (,) element.
AllowCurrencySymbol 货币符号($)。The currency ($) element.
Currency 所有元素。All elements. 但是,s 不能表示十六进制数或以指数表示法表示的数字。However, s 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 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 数据类型的范围,则该方法将引发 .NET Framework 和 .NET Core 2.2 及更早版本上的 OverflowExceptionIf 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 及更高版本中,如果 s 小于 Single.MinValueSingle.PositiveInfinity s 大于 Single.MaxValue,则返回 Single.NegativeInfinityOn .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. 有关分隔符的详细信息,请参阅 CurrencyDecimalSeparatorNumberDecimalSeparatorCurrencyGroupSeparatorNumberGroupSeparatorFor more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

另请参阅

适用于