How to make decimal.Parse accept multiple cultures

Viewed 2526

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;
    }
}
3 Answers
Related