แก้ไข

แชร์ผ่าน


Single.Parse Method

Definition

Converts the string representation of a number to its single-precision floating-point number equivalent.

Overloads

Parse(String)

Converts the string representation of a number to its single-precision floating-point number equivalent.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Parses a span of UTF-8 characters into a value.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parses a span of characters into a value.

Parse(String, NumberStyles)

Converts the string representation of a number in a specified style 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<Byte>, NumberStyles, IFormatProvider)

Parses a span of UTF-8 characters into a value.

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

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

Parse(String)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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

Parameters

s
String

A string that contains a number to convert.

Returns

A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

Exceptions

s does not represent a number in a valid format.

.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number less than Single.MinValue or greater than Single.MaxValue.

Examples

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

let values = 
    [| "100"; "(100)"; "-123,456,789"; "123.45e+6" 
       "+500"; "5e2"; "3.1416"; "600."; "-.123" 
       "-Infinity"; "-1E-16"; string Double.MaxValue
       string Single.MinValue; String.Empty |]

for value in values do
    try
        let number = Single.Parse value
        printfn $"{value} -> {number}"
    with
    | :? FormatException ->
        printfn $"'{value}' is not in a valid format."
    | :? OverflowException ->
        printfn $"{value} is outside the range of a Single."
// 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.

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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]

Elements in square brackets ([ and ]) are optional. The following table describes each element.

Element Description
ws A series of white space characters.
sign A negative sign symbol or a positive sign symbol. 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 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 A series of digits ranging from 0 to 9 that specify the fractional part of the number.
E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
exponential-digits A series of digits ranging from 0 to 9 that specify an exponent.

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

The s parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. For more information, see CurrentInfo. To parse a string by using the formatting information of a specific culture, use the Parse(String, IFormatProvider) or Parse(String, NumberStyles, IFormatProvider) method.

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.

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

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. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

See also

Applies to

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
Single.cs
Source:
Single.cs

Parses a span of UTF-8 characters into a value.

public:
 static float Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<float>::Parse;
public static float Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> single
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Single

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

Parses a span of characters into a value.

public:
 static float Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<float>::Parse;
public static float Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> single
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Single

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

Returns

The result of parsing s.

Implements

Applies to

Parse(String, NumberStyles)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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

Parameters

s
String

A string that contains a number to convert.

style
NumberStyles

A bitwise combination of enumeration values that indicates the style elements that can be present in s. A typical value to specify is Float combined with AllowThousands.

Returns

A single-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

Exceptions

s is not a number in a valid format.

.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than Single.MinValue or greater than Single.MaxValue.

style is not a NumberStyles value.

-or-

style includes the AllowHexSpecifier value.

Examples

The following example uses the Parse(String, NumberStyles) method to parse the string representations of Single values. 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.
open System
open System.Globalization
open System.Threading

let showNumericValue value (styles: NumberStyles) =
    try
        let number = Single.Parse(value, styles)
        printfn $"Converted '{value}' using {styles} to {number}."
    with :? FormatException ->
        printfn $"Unable to parse '{value}' with styles {styles}."
    printfn ""

[<EntryPoint>]
let main _ =
    // Set current thread culture to en-US.
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"
    
    // Parse a string in exponential notation with only the AllowExponent flag. 
    let value = "-1.063E-02"
    let styles = NumberStyles.AllowExponent
    showNumericValue value styles
    
    // Parse a string in exponential notation
    // with the AllowExponent and Number flags.
    let 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.
    let value = " $ 6,164.3299  "
    let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
    showNumericValue value styles
    
    // Parse negative value with thousands separator and decimal.
    let value = "(4,320.64)"
    let styles = NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float 
    showNumericValue value styles
    
    let styles = NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
    showNumericValue value styles
    0
// 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.

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:

The s parameter can contain the current culture's PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol. Depending on the value of style, it can also take the form:

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

ws A series of white-space characters. 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. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. The 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 (+). 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. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.

integral-digits 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. The current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag

. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

fractional-digits A series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.

E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.

exponential-digits A series of digits ranging from 0 to 9 that specify an exponent.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

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. The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. The following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles value Elements permitted in s in addition to digits
None The integral-digits element only.
AllowDecimalPoint The decimal point (.) and fractional-digits elements.
AllowExponent The "e" or "E" character, which indicates exponential notation. 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 The ws element at the beginning of s.
AllowTrailingWhite The ws element at the end of s.
AllowLeadingSign The sign element at the beginning of s.
AllowTrailingSign 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. However, s cannot represent a hexadecimal number or a number in exponential notation.
Float The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. The s parameter can also use exponential notation.
Number The ws, sign, thousands separator (,) and decimal point (.) elements.
Any All elements. However, s cannot represent a hexadecimal number.

Some examples of s are "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123", and "-Infinity".

The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. To specify the culture whose formatting information is used for the parse operation, call the Parse(String, NumberStyles, IFormatProvider) overload.

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.

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

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. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

See also

Applies to

Parse(String, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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(System::String ^ s, IFormatProvider ^ provider) = IParsable<float>::Parse;
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

Parameters

s
String

A string that contains a number to convert.

provider
IFormatProvider

An object that supplies culture-specific formatting information about s.

Returns

A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

Implements

Exceptions

s does not represent a number in a valid format.

.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number less than Single.MinValue or greater than Single.MaxValue.

Examples

The following example is the button click event handler of a Web form. It uses the array returned by the HttpRequest.UserLanguages property to determine the user's locale. It then instantiates a CultureInfo object that corresponds to that locale. 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

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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.

The s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags. 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]

Optional elements are framed in square brackets ([ and ]). Elements that contain the term "digits" consist of a series of numeric characters ranging from 0 to 9.

Element Description
ws A series of white-space characters.
sign A negative sign symbol (-) or a positive sign symbol (+).
integral-digits 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 A series of digits ranging from 0 to 9 that specify the fractional part of the number.
E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation.
exponential-digits A series of digits ranging from 0 to 9 that specify an exponent.

For more information about numeric formats, see the Formatting Types topic.

The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information. 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. The GetFormat method then returns the NumberFormatInfo object that provides information about the format of the s parameter. There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

  • You can pass a CultureInfo object that represents the culture that supplies formatting information. Its GetFormat method returns the NumberFormatInfo object that provides numeric formatting information for that culture.

  • You can pass the actual NumberFormatInfo object that provides numeric formatting information. (Its implementation of GetFormat just returns itself.)

  • You can pass a custom object that implements IFormatProvider. Its GetFormat method instantiates and returns the NumberFormatInfo object that provides formatting information.

If provider is null or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

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

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. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

Some examples of s are "100", "-123,456,789", "123.45e+6", "+500", "5e2", "3.1416", "600.", "-.123", and "-Infinity".

See also

Applies to

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs

Parses a span of UTF-8 characters into a value.

public static float Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> single
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Single

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

style
NumberStyles

A bitwise combination of number styles that can be present in utf8Text.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
public static float Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, 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.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Single

Parameters

s
ReadOnlySpan<Char>

A character span that contains the number to convert.

style
NumberStyles

A bitwise combination of enumeration values that indicate the style elements that can be present in s. A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

An object that supplies culture-specific formatting information about s.

Returns

A single-precision floating-point number that is equivalent to the numeric value or symbol specified in s.

Implements

Exceptions

s does not represent a numeric value.

style is not a NumberStyles value.

-or-

style is the AllowHexSpecifier value.

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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.

Applies to

Parse(String, NumberStyles, IFormatProvider)

Source:
Single.cs
Source:
Single.cs
Source:
Single.cs

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(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<float>::Parse;
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

Parameters

s
String

A string that contains a number to convert.

style
NumberStyles

A bitwise combination of enumeration values that indicates the style elements that can be present in s. A typical value to specify is Float combined with AllowThousands.

provider
IFormatProvider

An object that supplies culture-specific formatting information about s.

Returns

A single-precision floating-point number equivalent to the numeric value or symbol specified in s.

Implements

Exceptions

s does not represent a numeric value.

style is not a NumberStyles value.

-or-

style is the AllowHexSpecifier value.

.NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than Single.MinValue or greater than Single.MaxValue.

Examples

The following code example uses the Parse(String, NumberStyles, IFormatProvider) method to parse the string representations of Single values. 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.
open System
open System.Globalization

// Define a list of string values.
let 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.
let ci = CultureInfo ""
ci.NumberFormat.NumberGroupSizes <- [| 2 |]
ci.NumberFormat.NumberGroupSeparator <- "_"

// Define a list of format providers.
let providers = 
    [ CultureInfo "en-US"
      CultureInfo "nl-NL"
      ci ]

// Define a list of styles.
let styles = [ NumberStyles.Currency; NumberStyles.Float ]

// Iterate the list of format providers.
for provider in providers do
    printfn $"""Parsing using the {if provider.Name = String.Empty then "Invariant" else provider.Name} culture:"""
    // Parse each element in the array of string values.
    for value in values do
        for style in styles do
            try
                let number = Single.Parse(value, style, provider)
                printfn $"   {value} ({style}) -> {number}"
            with
            | :? FormatException ->
                printfn $"   '{value}' is invalid using {style}."
            | :? OverflowException ->
                printfn $"   '{value}' is out of the range of a Single."
    printfn ""

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

Remarks

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. In prior versions, including .NET Framework, parsing a value that was too large to represent resulted in failure.

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. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:

The s parameter can contain NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, or NumberFormatInfo.NaNSymbol for the culture specified by provider. Depending on the value of style, it can also take the form:

[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
ws A series of white-space characters. 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. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. The 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 (+). 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. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digits 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. The current culture's group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digits A series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
E The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digits A series of digits ranging from 0 to 9 that specify an exponent.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

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. The remaining System.Globalization.NumberStyles members control elements that may be present, but are not required to be present, in the input string. The following table indicates how individual NumberStyles flags affect the elements that may be present in s.

NumberStyles value Elements permitted in s in addition to digits
None The integral-digits element only.
AllowDecimalPoint The decimal point (.) and fractional-digits elements.
AllowExponent The "e" or "E" character, which indicates exponential notation. 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 The ws element at the beginning of s.
AllowTrailingWhite The ws element at the end of s.
AllowLeadingSign The sign element at the beginning of s.
AllowTrailingSign 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. However, s cannot represent a hexadecimal number or a number in exponential notation.
Float The ws element at the beginning or end of s, sign at the beginning of s, and the decimal point (.) symbol. The s parameter can also use exponential notation.
Number The ws, sign, thousands separator (,) and decimal point (.) elements.
Any All elements. However, s cannot represent a hexadecimal number.

The provider parameter is an IFormatProvider implementation. Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. Typically, provider can be any one of the following:

If provider is null, the NumberFormatInfo object for the current culture is used.

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

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. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

See also

Applies to