Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Decimal.Parse Método (String, NumberStyles)

Converts the String representation of a number in a specified style to its Decimal equivalent using the specified formatting style.

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

public static decimal Parse(
	string s,
	NumberStyles style
)

Parâmetros

s
Tipo: System.String
A String containing a number to convert.
style
Tipo: System.Globalization.NumberStyles
A bitwise combination of NumberStyles values that indicates the permitted format of s.A typical value to specify is Number.

Valor de retorno

Tipo: System.Decimal
The Decimal number equivalent to the number contained in s as specified by style.

ExceçãoCondição
ArgumentNullException

s is null.

ArgumentException

style is not a NumberStyles value.

-ou-

style is the AllowHexSpecifier value.

FormatException

s is not in the correct format.

OverflowException

s represents a number less than MinValue or greater than MaxValue

Parameter s contains a number of the form:

[ws]Dígitos [usuário] [.fractional-dígitos] [ws]

Items in square brackets ('[' and ']') are opcional, and Outro items are as follows.

ws

Espaço em Branco opcional.

Sinal

Uma entrada opcional.

Dígitos

Uma seqüência de dígitos que varia de 0 a 9.

'.'

Um símbolo cultura-específicas do ponto decimal.

fracionária-dígitos

Uma seqüência de dígitos que varia de 0 a 9.

The style parameter specifies the permitted format of the numeric string.It must be a combination of bit flags from the NumberStyles enumeration.If style is null, s is interpreted using the NumberStyles.Number style.

Parameter s is parsed using the formatting information in a NumberFormatInfo initialized for the current system culture.Para maiores informações, veja CurrentInfo.

A Decimal has 29 digits of precision.If s represents a number that has more than 29 digits, but has a fractional part and is within the range of MaxValue and MinValue, the number is rounded, not truncated, to 29 digits using rounding to nearest.

If during a parse operation a separator is encountered in the s parameter, 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 Decimal values with several overloads of the Parse method.

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

class DecimalParseDemo
{
    static void DecimalParse( NumberStyles styles, 
        IFormatProvider provider )
    {
        string[ ] decimalFormats = { "9876543210.9876543210", 
            "9876543210,9876543210", "(9876543210,9876543210)", 
            "9,876,543,210,987,654.3210", 
            "9.876.543.210.987.654,3210", 
            "98_7654_3210_9876,543210" };

        // Parse each string in the decimalFormats array, using 
        // NumberStyles and IFormatProvider, if specified.
        foreach ( string decimalString in decimalFormats )
        {
            decimal decimalNumber;

            // Display the first part of the output line.
            Console.Write("  Parse of {0,-29}", 
                String.Format( "\"{0}\"", decimalString ) );

            try
            {
                // Use the appropriate Decimal.Parse overload, 
                // based on the parameters that are specified.
                if( provider == null )
                    if ( styles < 0 )
                        decimalNumber = 
                            Decimal.Parse( decimalString );
                    else
                        decimalNumber = Decimal.Parse( 
                            decimalString, styles );
                else 
                    if( styles < 0 )
                        decimalNumber = Decimal.Parse(
                            decimalString, provider );
                    else
                        decimalNumber = Decimal.Parse(
                            decimalString, styles, provider );

                // Display the resulting value if Parse succeeded.
                Console.WriteLine( "succeeded: {0}", 
                    decimalNumber );

            }
            catch( Exception ex )
            {
                // Display the exception message if Parse failed.
                // Truncate it to fit on the output line.
                Console.WriteLine( "failed: {0}", 
                    ex.Message.Substring( 0, 31 ) );
            }
        }
    }

    static void Main( )
    {
        Console.WriteLine( "This example of\n  Decimal.Parse( " +
            "String ),\n  Decimal.Parse( String, NumberStyles " +
            "),\n  Decimal.Parse( String, IFormatProvider ), " +
            "and\n  Decimal.Parse( String, NumberStyles, " +
            "IFormatProvider )\ngenerates the " +
            "following output when run in the [{0}] culture.", 
            CultureInfo.CurrentCulture.Name );
        Console.WriteLine( "Several string representations " +
            "of Decimal values are parsed." );

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

        // Use the NumberStyle for Currency.
        Console.WriteLine( "\nNumberStyles.Currency " +
            "is used; IFormatProvider is not used:" );
        DecimalParse( 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 );
        DecimalParse( (NumberStyles)(-1), culture );

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

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

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

NumberStyles and IFormatProvider are not used; current culture is [en-US]:
  Parse of "9876543210.9876543210"      succeeded: 9876543210.9876543210
  Parse of "9876543210,9876543210"      succeeded: 98765432109876543210
  Parse of "(9876543210,9876543210)"    failed: Input string was not in a corre
  Parse of "9,876,543,210,987,654.3210" succeeded: 9876543210987654.3210
  Parse of "9.876.543.210.987.654,3210" failed: Input string was not in a corre
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles.Currency is used; IFormatProvider is not used:
  Parse of "9876543210.9876543210"      succeeded: 9876543210.9876543210
  Parse of "9876543210,9876543210"      succeeded: 98765432109876543210
  Parse of "(9876543210,9876543210)"    succeeded: -98765432109876543210
  Parse of "9,876,543,210,987,654.3210" succeeded: 9876543210987654.3210
  Parse of "9.876.543.210.987.654,3210" failed: Input string was not in a corre
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles is not used; [nl-NL] culture IFormatProvider is used:
  Parse of "9876543210.9876543210"      succeeded: 98765432109876543210
  Parse of "9876543210,9876543210"      succeeded: 9876543210.9876543210
  Parse of "(9876543210,9876543210)"    failed: Input string was not in a corre
  Parse of "9,876,543,210,987,654.3210" failed: Input string was not in a corre
  Parse of "9.876.543.210.987.654,3210" succeeded: 9876543210987654.3210
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles.Currency is used, group size = 4, separator = "_":
  Parse of "9876543210.9876543210"      succeeded: 98765432109876543210
  Parse of "9876543210,9876543210"      succeeded: 9876543210.9876543210
  Parse of "(9876543210,9876543210)"    succeeded: -9876543210.9876543210
  Parse of "9,876,543,210,987,654.3210" failed: Input string was not in a corre
  Parse of "9.876.543.210.987.654,3210" succeeded: 9876543210987654.3210
  Parse of "98_7654_3210_9876,543210"   succeeded: 98765432109876.543210
*/


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

class DecimalParseDemo
{
    static void DecimalParse(NumberStyles styles, IFormatProvider provider) 
    {
        String decimalFormats[] =  {"9876543210.9876543210", 
            "9876543210,9876543210", "(9876543210,9876543210)", 
            "9,876,543,210,987,654.3210", 
            "9.876.543.210.987.654,3210", 
            "98_7654_3210_9876,543210"};

        // Parse each string in the decimalFormats array, using 
        // NumberStyles and IFormatProvider, if specified.
        for (int iCtr = 0; iCtr < decimalFormats.length; iCtr++) {
            String decimalString = decimalFormats[iCtr];
            System.Decimal decimalNumber;

            // Display the first part of the output line.
            Console.Write("  Parse of {0,-29}", String.Format("\"{0}\"",
                decimalString));

            try {
                // Use the appropriate Decimal.Parse overload, 
                // based on the parameters that are specified.
                if ( provider == null  ) {
                    if (styles.CompareTo(NumberStyles.None) < 0) {
                        decimalNumber = Decimal.Parse(decimalString);
                    }
                    else {
                        decimalNumber = Decimal.Parse(decimalString, styles);
                    }
                }
                else {
                    if (styles.CompareTo(NumberStyles.None) < 0) {
                        decimalNumber = Decimal.Parse(decimalString, provider);
                    }
                    else {
                        decimalNumber = Decimal.Parse(decimalString,
                                                        styles, provider);
                    }
                } 
                // Display the resulting value if Parse succeeded.
                Console.WriteLine("succeeded: {0}", decimalNumber);
            }

            catch(System.Exception  ex) {
                // Display the exception message if Parse failed.
                // Truncate it to fit on the output line.
                Console.WriteLine("failed: {0}",
                    ex.get_Message().Substring(0, 31));
            }
        }
    } //DecimalParse

    public static void main(String[] args)
    {
        Console.WriteLine("This example of\n  Decimal.Parse( " 
            + "String ),\n  Decimal.Parse( String, NumberStyles "  
            + "),\n  Decimal.Parse( String, IFormatProvider ), " 
            + "and\n  Decimal.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 Decimal values are parsed."));

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

        // Use the NumberStyle for Currency.
        Console.WriteLine(("\nNumberStyles.Currency " 
            + "is used; IFormatProvider is not used:"));
        DecimalParse(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).equals("nl")) ? "en-US" : "nl-NL";
        CultureInfo culture =  new CultureInfo(cultureName);

        Console.WriteLine("\nNumberStyles is not used; [{0}] "
            + "culture IFormatProvider is used:", culture.get_Name());
        DecimalParse(((NumberStyles)(-1)), culture);

        // Get the NumberFormatInfo object from CultureInfo, and
        // then change the digit group size to 4 and the digit
        // separator to '_'.
        NumberFormatInfo numInfo = culture.get_NumberFormat();
        numInfo.set_NumberGroupSizes(new int[]{4});
        numInfo.set_NumberGroupSeparator("_");

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

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

NumberStyles and IFormatProvider are not used; current culture is [en-US]:
  Parse of "9876543210.9876543210"      succeeded: 9876543210.9876543210
  Parse of "9876543210,9876543210"      succeeded: 98765432109876543210
  Parse of "(9876543210,9876543210)"    failed: Input string was not in a corre
  Parse of "9,876,543,210,987,654.3210" succeeded: 9876543210987654.3210
  Parse of "9.876.543.210.987.654,3210" failed: Input string was not in a corre
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles.Currency is used; IFormatProvider is not used:
  Parse of "9876543210.9876543210"      succeeded: 9876543210.9876543210
  Parse of "9876543210,9876543210"      succeeded: 98765432109876543210
  Parse of "(9876543210,9876543210)"    succeeded: -98765432109876543210
  Parse of "9,876,543,210,987,654.3210" succeeded: 9876543210987654.3210
  Parse of "9.876.543.210.987.654,3210" failed: Input string was not in a corre
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles is not used; [nl-NL] culture IFormatProvider is used:
  Parse of "9876543210.9876543210"      succeeded: 98765432109876543210
  Parse of "9876543210,9876543210"      succeeded: 9876543210.9876543210
  Parse of "(9876543210,9876543210)"    failed: Input string was not in a corre
  Parse of "9,876,543,210,987,654.3210" failed: Input string was not in a corre
  Parse of "9.876.543.210.987.654,3210" succeeded: 9876543210987654.3210
  Parse of "98_7654_3210_9876,543210"   failed: Input string was not in a corre

NumberStyles.Currency is used, group size = 4, separator = "_":
  Parse of "9876543210.9876543210"      succeeded: 98765432109876543210
  Parse of "9876543210,9876543210"      succeeded: 9876543210.9876543210
  Parse of "(9876543210,9876543210)"    succeeded: -9876543210.9876543210
  Parse of "9,876,543,210,987,654.3210" failed: Input string was not in a corre
  Parse of "9.876.543.210.987.654,3210" succeeded: 9876543210987654.3210
  Parse of "98_7654_3210_9876,543210"   succeeded: 98765432109876.543210
*/


Contribuições da comunidade

ADICIONAR
Mostrar: