Share via


Single.Parse Method (String, NumberStyles)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function Parse ( _
    s As String, _
    style As NumberStyles _
) As Single
public static float Parse(
    string s,
    NumberStyles style
)

Parameters

  • s
    Type: System.String
    A string representing a number to convert.

Return Value

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

Exceptions

Exception Condition
ArgumentNullException

s is nulla null reference (Nothing in Visual Basic).

FormatException

s is not a number in a valid format.

OverflowException

s represents a number less than MinValue or greater than MaxValue.

ArgumentException

style is not a NumberStyles value.

-or-

style is the AllowHexSpecifier value.

Remarks

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.

A string with digits only (which corresponds to the NumberStyles.None style) always parses successfully. 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 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.

CurrencyGroupSeparator, and NumberGroupSeparator.

Examples

The following code example parses String representations of Single values with the Parse method, using NumberStyles values.

' Example of the Single.Parse( ) methods.
Imports System.Globalization

Module Example

   ' Get the exception type name; remove the namespace prefix.
   Function GetExceptionType(ByVal ex As Exception) As String

      Dim exceptionType As String = ex.GetType().ToString()
      Return exceptionType.Substring( _
          exceptionType.LastIndexOf("."c) + 1)
   End Function

   Sub SingleParse(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal styles As NumberStyles, _
       ByVal provider As IFormatProvider)

      Dim singleFormats As String() = { _
          " 987.654E-2", " 987,654E-2", "(98765,43210)", _
          "9,876,543.210", "9.876.543,210", "98_76_54_32,19"}

      ' Parse each string in the singleFormats array, using 
      ' NumberStyles and IFormatProvider, if specified.
      Dim singleString As String
      For Each singleString In singleFormats

         Dim singleNumber As Single

         ' Display the first part of the output line.
         outputBlock.Text &= String.Format("  Parse of {0,-20}", _
             String.Format("""{0}""", singleString))

         ' Use the appropriate Single.Parse overload, based on 
         ' the parameters that are specified.
         Try
            If provider Is Nothing Then
               If styles < 0 Then
                  singleNumber = Single.Parse(singleString)
               Else
                  singleNumber = _
                      Single.Parse(singleString, styles)
               End If
            ElseIf styles < 0 Then
               singleNumber = _
                   Single.Parse(singleString, provider)
            Else
               singleNumber = Single.Parse( _
                   singleString, styles, provider)
            End If

            ' Display the resulting value if Parse succeeded.
            outputBlock.Text &= String.Format("success: {0}", singleNumber) & vbCrLf

            ' Display the exception type if Parse failed.
         Catch ex As Exception
            outputBlock.Text &= String.Format("failed:  {0}", _
                GetExceptionType(ex)) & vbCrLf
         End Try
      Next singleString
   End Sub

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      outputBlock.Text &= String.Format("This example of" & vbCrLf & _
          "  Single.Parse( String )," & vbCrLf & _
          "  Single.Parse( String, NumberStyles )," & vbCrLf & _
          "  Single.Parse( String, IFormatProvider ), and" & _
          vbCrLf & "  Single.Parse( String, NumberStyles, " & _
          "IFormatProvider )" & vbCrLf & "generates the " & _
          "following output when run in the [{0}] culture.", _
          CultureInfo.CurrentCulture.Name) & vbCrLf
      outputBlock.Text &= String.Format("Several string representations " & _
          "of Single values are parsed.") & vbCrLf

      ' Do not use IFormatProvider or NumberStyles.
      outputBlock.Text &= String.Format(vbCrLf & _
          "NumberStyles and IFormatProvider are not " & _
          "used; current culture is [{0}]:", _
          CultureInfo.CurrentCulture.Name) & vbCrLf
      SingleParse(outputBlock, CType(-1, NumberStyles), Nothing)

      ' Use the NumberStyle for Currency.
      outputBlock.Text &= String.Format(vbCrLf & "NumberStyles.Currency " & _
          "is used; IFormatProvider is not used:") & vbCrLf
      SingleParse(outputBlock, NumberStyles.Currency, Nothing)

      ' Create a CultureInfo object for another culture. Use
      ' [Dutch - The Netherlands] unless the current culture
      ' is Dutch language. In that case use [English - U.S.].
      Dim cultureName As String = IIf( _
          CultureInfo.CurrentCulture.Name.Substring(0, 2) = _
              "nl", "en-US", "nl-NL")
      Dim culture As New CultureInfo(cultureName)

      outputBlock.Text &= String.Format(vbCrLf & _
          "NumberStyles is not used; [{0}] culture " & _
          "IFormatProvider is used:", culture.Name) & vbCrLf
      SingleParse(outputBlock, CType(-1, NumberStyles), culture)

      ' Get the NumberFormatInfo object from CultureInfo, and
      ' then change the digit group size to 2 and the digit
      ' separator to '_'.
      Dim numInfo As NumberFormatInfo = culture.NumberFormat
      numInfo.NumberGroupSizes = New Integer() {2}
      numInfo.NumberGroupSeparator = "_"

      ' Use the NumberFormatInfo object as the IFormatProvider.
      outputBlock.Text &= String.Format(vbCrLf & _
          "NumberStyles.Currency is used, group size = 2, " & _
          "separator = ""_"":") & vbCrLf
      SingleParse(outputBlock, NumberStyles.Currency, numInfo)
   End Sub
End Module

' This example of
'   Single.Parse( String ),
'   Single.Parse( String, NumberStyles ),
'   Single.Parse( String, IFormatProvider ), and
'   Single.Parse( String, NumberStyles, IFormatProvider )
' generates the following output when run in the [en-US] culture.
' Several string representations of Single values are parsed.
' 
' NumberStyles and IFormatProvider are not used; current culture is [en-US]:
'   Parse of " 987.654E-2"       success: 9.87654
'   Parse of " 987,654E-2"       success: 9876.54
'   Parse of "(98765,43210)"     failed:  FormatException
'   Parse of "9,876,543.210"     success: 9876543
'   Parse of "9.876.543,210"     failed:  FormatException
'   Parse of "98_76_54_32,19"    failed:  FormatException
' 
' NumberStyles.Currency is used; IFormatProvider is not used:
'   Parse of " 987.654E-2"       failed:  FormatException
'   Parse of " 987,654E-2"       failed:  FormatException
'   Parse of "(98765,43210)"     success: -9.876543E+09
'   Parse of "9,876,543.210"     success: 9876543
'   Parse of "9.876.543,210"     failed:  FormatException
'   Parse of "98_76_54_32,19"    failed:  FormatException
' 
' NumberStyles is not used; [nl-NL] culture IFormatProvider is used:
'   Parse of " 987.654E-2"       success: 9876.54
'   Parse of " 987,654E-2"       success: 9.87654
'   Parse of "(98765,43210)"     failed:  FormatException
'   Parse of "9,876,543.210"     failed:  FormatException
'   Parse of "9.876.543,210"     success: 9876543
'   Parse of "98_76_54_32,19"    failed:  FormatException
' 
' NumberStyles.Currency is used, group size = 2, separator = "_":
'   Parse of " 987.654E-2"       failed:  FormatException
'   Parse of " 987,654E-2"       failed:  FormatException
'   Parse of "(98765,43210)"     success: -98765.43
'   Parse of "9,876,543.210"     failed:  FormatException
'   Parse of "9.876.543,210"     success: 9876543
'   Parse of "98_76_54_32,19"    success: 9.876543E+07
// Example of the Single.Parse( ) methods.
using System;
using System.Globalization;

class Example
{
   // Get the exception type name; remove the namespace prefix.
   static string GetExceptionType(Exception ex)
   {
      string exceptionType = ex.GetType().ToString();
      return exceptionType.Substring(
          exceptionType.LastIndexOf('.') + 1);
   }

   // Parse each string in the singleFormats array, using 
   // NumberStyles and IFormatProvider, if specified.
   static void SingleParse(System.Windows.Controls.TextBlock outputBlock, NumberStyles styles,
       IFormatProvider provider)
   {
      string[] singleFormats = {
            " 987.654E-2",   " 987,654E-2",    "(98765,43210)", 
            "9,876,543.210", "9.876.543,210",  "98_76_54_32,19" };

      foreach (string singleString in singleFormats)
      {
         float singleNumber;

         // Display the first part of the output line.
         outputBlock.Text += String.Format("  Parse of {0,-20}",
             String.Format("\"{0}\"", singleString));

         try
         {
            // Use the appropriate Single.Parse overload, based 
            // on the parameters that are specified.
            if (provider == null)
            {
               if (styles < 0)
                  singleNumber = Single.Parse(singleString);
               else
                  singleNumber =
                      Single.Parse(singleString, styles);
            }
            else if (styles < 0)
               singleNumber =
                   Single.Parse(singleString, provider);
            else
               singleNumber =
                   Single.Parse(singleString, styles, provider);

            // Display the resulting value if Parse succeeded.
            outputBlock.Text += String.Format("success: {0}", singleNumber) + "\n";
         }
         catch (Exception ex)
         {
            // Display the exception type if Parse failed.
            outputBlock.Text += String.Format("failed:  {0}",
                GetExceptionType(ex)) + "\n";
         }
      }
   }

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      outputBlock.Text += String.Format("This example of\n" +
          "  Single.Parse( String ),\n" +
          "  Single.Parse( String, NumberStyles ),\n" +
          "  Single.Parse( String, IFormatProvider ), and\n" +
          "  Single.Parse( String, NumberStyles, " +
          "IFormatProvider )\ngenerates the " +
          "following output when run in the [{0}] culture.",
          CultureInfo.CurrentCulture.Name) + "\n";
      outputBlock.Text += String.Format("Several string representations " +
          "of Single values are parsed.") + "\n";

      // Do not use IFormatProvider or NumberStyles.
      outputBlock.Text += String.Format("\nNumberStyles and IFormatProvider " +
          "are not used; current culture is [{0}]:",
          CultureInfo.CurrentCulture.Name) + "\n";
      SingleParse(outputBlock, ((NumberStyles)(-1)), null);

      // Use the NumberStyle for Currency.
      outputBlock.Text += String.Format("\nNumberStyles.Currency " +
          "is used; IFormatProvider is not used:") + "\n";
      SingleParse(outputBlock, NumberStyles.Currency, null);

      // Create a CultureInfo object for another culture. Use
      // [Dutch - The Netherlands] unless the current culture
      // is Dutch language. In that case use [English - U.S.].
      string cultureName =
          CultureInfo.CurrentCulture.Name.Substring(0, 2) == "nl" ?
              "en-US" : "nl-NL";
      CultureInfo culture = new CultureInfo(cultureName);

      outputBlock.Text += String.Format("\nNumberStyles is not used; " +
          "[{0}] culture IFormatProvider is used:",
          culture.Name) + "\n";
      SingleParse(outputBlock, ((NumberStyles)(-1)), culture);

      // Get the NumberFormatInfo object from CultureInfo, and
      // then change the digit group size to 2 and the digit
      // separator to '_'.
      NumberFormatInfo numInfo = culture.NumberFormat;
      numInfo.NumberGroupSizes = new int[] { 2 };
      numInfo.NumberGroupSeparator = "_";

      // Use the NumberFormatInfo object as the IFormatProvider.
      outputBlock.Text += String.Format("\nNumberStyles.Currency is used, " +
          "group size = 2, separator = \"_\":") + "\n";
      SingleParse(outputBlock, NumberStyles.Currency, numInfo);
   }
}

/*
This example of
  Single.Parse( String ),
  Single.Parse( String, NumberStyles ),
  Single.Parse( String, IFormatProvider ), and
  Single.Parse( String, NumberStyles, IFormatProvider )
generates the following output when run in the [en-US] culture.
Several string representations of Single values are parsed.

NumberStyles and IFormatProvider are not used; current culture is [en-US]:
  Parse of " 987.654E-2"       success: 9.87654
  Parse of " 987,654E-2"       success: 9876.54
  Parse of "(98765,43210)"     failed:  FormatException
  Parse of "9,876,543.210"     success: 9876543
  Parse of "9.876.543,210"     failed:  FormatException
  Parse of "98_76_54_32,19"    failed:  FormatException

NumberStyles.Currency is used; IFormatProvider is not used:
  Parse of " 987.654E-2"       failed:  FormatException
  Parse of " 987,654E-2"       failed:  FormatException
  Parse of "(98765,43210)"     success: -9.876543E+09
  Parse of "9,876,543.210"     success: 9876543
  Parse of "9.876.543,210"     failed:  FormatException
  Parse of "98_76_54_32,19"    failed:  FormatException

NumberStyles is not used; [nl-NL] culture IFormatProvider is used:
  Parse of " 987.654E-2"       success: 9876.54
  Parse of " 987,654E-2"       success: 9.87654
  Parse of "(98765,43210)"     failed:  FormatException
  Parse of "9,876,543.210"     failed:  FormatException
  Parse of "9.876.543,210"     success: 9876543
  Parse of "98_76_54_32,19"    failed:  FormatException

NumberStyles.Currency is used, group size = 2, separator = "_":
  Parse of " 987.654E-2"       failed:  FormatException
  Parse of " 987,654E-2"       failed:  FormatException
  Parse of "(98765,43210)"     success: -98765.43
  Parse of "9,876,543.210"     failed:  FormatException
  Parse of "9.876.543,210"     success: 9876543
  Parse of "98_76_54_32,19"    success: 9.876543E+07
*/

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.