Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make decimal.Parse accept multiple cultures

I need to accept 3 decimal data formats in my app:

  • 123456,78 => 123456.78
  • 123,456.78 => 123456.78
  • 123456.78 => 123456.78

I cannot assume that one format will be used in particular situation. What I need is get a decimal value from a string no matter in which format it's given.

Is there a smart way to do this?

I was trying to use

var culture = CultureInfo.CreateSpecificCulture("en-US");

but this doesn't seem to work on wp7.

So far I've done this:

public static class Extensions
{

    public static decimal toDecimal(this string s)
    {
        decimal res;

        int comasCount=0;
        int periodsCount=0;

        foreach (var c in s)
        {
            if (c == ',')
                comasCount++;
            else if (c == '.')
                periodsCount++;
        }

        if (periodsCount > 1)
            throw new FormatException();
        else if(periodsCount==0 && comasCount > 1)
            throw new FormatException();

        if(comasCount==1)
        {
            // pl-PL
            //parse here
        }else
        {
            //en-US
            //parse here
        }

        return res;
    }
}
like image 407
Andrzej Gis Avatar asked Aug 20 '12 23:08

Andrzej Gis


People also ask

How to Parse to decimal in C#?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.

What is the purpose of the decimal parse method?

Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information.

How to change decimal to string?

To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.

How to convert decimal to string in ASP net C#?

ToString() is a method in C# that is called on decimal values. It converts a numeric value that is a decimal to a string.


1 Answers

Try using var culture = new CultureInfo("en-US"); to create the culture. Passing that culture to decimal.Parse or decimal.TryParse will parse the text appropriately for each culture.

Now, keep in mind that each culture may parse the text without failure but not parse it the way it's represented for the original culture. For example decimal.TryParse("1000,314", NumberStyles.Number, new CultureInfo("en-US"), out result) will result success and 1000314m, not 1000.314m. Whereas decimal.TryParse("1000,314", NumberStyles.Number, new CultureInfo("fr-FR"), out result) will result in 1000.314m.

like image 162
Peter Ritchie Avatar answered Oct 26 '22 16:10

Peter Ritchie