Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

Single.Parse Method (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.

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

public static float Parse (
	string s,
	NumberStyles style,
	IFormatProvider provider
)
public static float Parse (
	String s, 
	NumberStyles style, 
	IFormatProvider provider
)
public static function Parse (
	s : String, 
	style : NumberStyles, 
	provider : IFormatProvider
) : float

Parameters

s

A string representing a number to convert.

style

A bitwise combination of NumberStyles values that indicates the permitted format of s. A typical value to specify is Float combined with AllowThousands.

provider

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

Return Value

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

ArgumentNullException

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

FormatException

s is not a numeric value.

ArgumentException

style is not a NumberStyles value.

-or-

style is the AllowHexSpecifier value.

The s parameter can contain PositiveInfinitySymbol, NegativeInfinitySymbol, NaNSymbol, or a string of the form:

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

Optional items are framed in square brackets ([ and ]). Items containing the term "digits" consist of a series of numeric characters ranging from 0 to 9.

ws

A series of white space characters.

sign

A negative sign or positive sign symbol.

integral-digits

A series of digits specifying 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.) Integral-digits can be absent if there are fractional-digits.

'.'

A culture-specific decimal point symbol.

fractional-digits

A series of digits specifying the fractional part of the number.

'e'

An uppercase or lowercase character 'e', indicating exponential (scientific) notation.

exponential-digits

A series of digits specifying an exponent.

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

This version of Parse uses the specified NumberStyles and the specified number format information. If provider is a null reference (Nothing in Visual Basic) or a NumberFormatInfo cannot be obtained, the formatting information for the current system culture is used.

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

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.

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

// Example of the Single.Parse( ) methods.
using System;
using System.Globalization;

class SingleParseDemo
{
    // 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( 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.
            Console.Write( "  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.
                Console.WriteLine( "success: {0}", singleNumber );
            }
            catch( Exception ex )
            {
                // Display the exception type if Parse failed.
                Console.WriteLine( "failed:  {0}", 
                    GetExceptionType( ex ) );
            }
        }
    }
    
    public static void Main( )
    {
        Console.WriteLine( "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 );
        Console.WriteLine( "Several string representations " +
            "of Single values are parsed." );

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

        // Use the NumberStyle for Currency.
        Console.WriteLine( "\nNumberStyles.Currency " +
            "is used; IFormatProvider is not used:" );
        SingleParse( 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 );
            
        Console.WriteLine( "\nNumberStyles is not used; " +
            "[{0}] culture IFormatProvider is used:", 
            culture.Name );
        SingleParse( ( (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.
        Console.WriteLine( "\nNumberStyles.Currency is used, " +
            "group size = 2, separator = \"_\":" );
        SingleParse( 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
*/ 

// Example of the Single.Parse( ) methods.
import System.*;
import System.Globalization.*;
import System.Exception;

class SingleParseDemo
{
    // 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));
    } //GetExceptionType

    // Parse each string in the singleFormats array, using 
    // NumberStyles and IFormatProvider, if specified.
    static void SingleParse(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" };
        for(int iCtr = 0; iCtr < singleFormats.length; iCtr++) {
            String singleString = singleFormats[iCtr];
            float singleNumber;

            // Display the first part of the output line.
            Console.Write("  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.GetHashCode() < 0) {
                        singleNumber = Single.Parse(singleString);
                    }
                    else {
                        singleNumber = Single.Parse(singleString, styles);
                    }
                }
                else {
                    if(styles.GetHashCode() < 0) {
                        singleNumber = Single.Parse(singleString, provider);
                    }
                    else {
                        singleNumber = Single.Parse(singleString, styles, 
                            provider);
                    }
                }

                // Display the resulting value if Parse succeeded.
                Console.WriteLine("success: {0}", 
                    new Object[] { new Float(singleNumber) });
            }
            catch(System.Exception ex) {
                // Display the exception type if Parse failed.
                Console.WriteLine("failed:  {0}", GetExceptionType(ex));
            }
        }
    } //SingleParse

    public static void main(String[] args)
    {
        Console.WriteLine("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.get_CurrentCulture().get_Name());
        Console.WriteLine(("Several string representations "
            + "of Single values are parsed."));

        // Do not use IFormatProvider or NumberStyles.
        Console.WriteLine("\nNumberStyles and IFormatProvider " 
            + "are not used; current culture is [{0}]:", 
            CultureInfo.get_CurrentCulture().get_Name());
        SingleParse(((NumberStyles)(-1)), null);

        // Use the NumberStyle for Currency.
        Console.WriteLine(("\nNumberStyles.Currency "
            + "is used; IFormatProvider is not used:"));
        SingleParse(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.get_CurrentCulture().
            get_Name().Substring(0, 2).equalsIgnoreCase("nl")) 
            ? "en-US" : "nl-NL";
        CultureInfo culture = new CultureInfo(cultureName);
        Console.WriteLine("\nNumberStyles is not used; " + 
            "[{0}] culture IFormatProvider is used:", culture.get_Name());
        SingleParse(((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.get_NumberFormat();
        numInfo.set_NumberGroupSizes(new int[] { 2 });
        numInfo.set_NumberGroupSeparator("_");

        // Use the NumberFormatInfo object as the IFormatProvider.
        Console.WriteLine(("\nNumberStyles.Currency is used, "
            + "group size = 2, separator = \"_\":"));
        SingleParse(NumberStyles.Currency, numInfo);
    } //main
} //SingleParseDemo

/*
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+9
  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+7
*/

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.