roadsunknown
roadsunknown

Reputation: 3210

Convert String to Double with Known Format

I need to convert a string back to a double, but the string is not always the same format. In one case it is "N0", in another "#,##", and yet another is currency "C0". The good thing is, I know what format the string is in as earlier in the process it was converted from double to string.

How can I convert back to a double. The numeric only values double.parse or Convert.ToDouble with ease, but the currency values do not.

string format = "{0:C0}";
double dollar = 1,234.00;
string dollarString = String.Format(format, doubleValue); // == "$1,234"
double newDollar = Convert.ToDouble(dollarString); // Fails

This last line is where the issue is. I'm assuming I need to use IFormatProvider or Culture or something, but I'm not exactly sure.

I cannot specifically reference the format is a Currency as the "format" isn't always a currency.

Ideas?

Upvotes: 1

Views: 247

Answers (2)

Fabian Bigler
Fabian Bigler

Reputation: 10895

If you're using CultureInfo.CurrentCulture make sure to you set the CurrentCulture of your thread.

Else it can end up in parsing it the wrong way (depending on the language settings on your computer).

 Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); 

Then you can safely use this:

double.TryParse(dollarString, NumberStyles.Any, 
CultureInfo.CurrentCulture.NumberFormat, out newDollar);

Alternatively, you can create a function like this (To get the right format without setting the culture).

side note: In Switzerland, this could cause troubles because the euros can still be parsed. So 5,05 (€) would successfully be parsed to 505 (CHF). Trust me, you don't want this to happen.

public static double GetDouble(string value, double defaultValue)
{
    double numberToConvert;

    if (!double.TryParse(value, System.Globalization.NumberStyles.Any, 
CultureInfo.CurrentCulture, out numberToConvert) &&
        !double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.GetCultureInfo("en-US"), out numberToConvert) &&
        !double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture, out numberToConvert))
    {
        numberToConvert= defaultValue;
    }

    return numberToConvert;
}

Upvotes: 0

roadsunknown
roadsunknown

Reputation: 3210

As I was typing this I came up with the following. Further feedback on whether this is a good way of doing it or if I might run into issues later.

double newDollar;
double.TryParse(dollarString, NumberStyles.Any, CultureInfo.CurrentCulture.NumberFormat, out newDollar);

Upvotes: 1

Related Questions