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

StackOverflow https://stackoverflow.com/questions/14747799

문제

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

도움이 되었습니까?

해결책 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)

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top