简体   繁体   中英

How i can convert string values in formats “1.123” and “1,123” to double by single double.TryParse?

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

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;
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM