Question

I have an incoming source of string values representing double values with "." and "," delimiter and my program would run on PCs with different settings of delimiter ("," or ",")
Which way can I convert it with single line without trying first convert ".", then if fail, try ","?
I tried some combinations like that:

    string dot_val = "1.12";
    string non_dot_val = "1,12";

    double dot_double = 0, non_dot_double = 0;

    bool dot_res = double.TryParse(dot_val, NumberStyles.Any, CultureInfo.CurrentCulture, out dot_double);
    bool non_dot_res = double.TryParse(non_dot_val, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentCulture, out non_dot_double);

But one of the attempts to convert is always fail.
If tell it shortly, I need an universal function to convert "." or "," delimited double values into double

Was it helpful?

Solution 2

The easiest way is to replace ',' by '.' and parse the result using the invariant culture setting:

double.TryParse(
          dot_val.Replace(',','.'), 
          NumberStyles.Any, 
          CultureInfo.InvariantCulture, 
          out dot_double);

The only limitation of this is that you shouldn't have grouping in your number (like 123,000.45)

OTHER TIPS

Well, the current culture tells you whether . or , is the decimal separator. If you want your function to parse both formats, you need to pass in a culture that has the respective separator. In your example:

public double UniveralParse(string value)
{
    double result;

    // If we can not parse the "." format...
    if (!double.TryParse(value, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result))
        // And also can not parse the "," format...
        if (!double.TryParse(value, NumberStyles.Any, CultureInfo.GetCultureInfo("de-DE"), out result))
            // we throw an exception
            throw new ArgumentException("value is not in expected format!");

    // Otherwise we can return the value
    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top