How do I parse a string with a decimal point to a double?

前端 未结 19 1547
孤街浪徒
孤街浪徒 2020-11-22 06:47

I want to parse a string like \"3.5\" to a double. However,

double.Parse(\"3.5\") 

yields 35 and

double.Pars         


        
19条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 07:04

    My two cents on this topic, trying to provide a generic, double conversion method:

    private static double ParseDouble(object value)
    {
        double result;
    
        string doubleAsString = value.ToString();
        IEnumerable doubleAsCharList = doubleAsString.ToList();
    
        if (doubleAsCharList.Where(ch => ch == '.' || ch == ',').Count() <= 1)
        {
            double.TryParse(doubleAsString.Replace(',', '.'),
                System.Globalization.NumberStyles.Any,
                CultureInfo.InvariantCulture,
                out result);
        }
        else
        {
            if (doubleAsCharList.Where(ch => ch == '.').Count() <= 1
                && doubleAsCharList.Where(ch => ch == ',').Count() > 1)
            {
                double.TryParse(doubleAsString.Replace(",", string.Empty),
                    System.Globalization.NumberStyles.Any,
                    CultureInfo.InvariantCulture,
                    out result);
            }
            else if (doubleAsCharList.Where(ch => ch == ',').Count() <= 1
                && doubleAsCharList.Where(ch => ch == '.').Count() > 1)
            {
                double.TryParse(doubleAsString.Replace(".", string.Empty).Replace(',', '.'),
                    System.Globalization.NumberStyles.Any,
                    CultureInfo.InvariantCulture,
                    out result);
            }
            else
            {
                throw new ParsingException($"Error parsing {doubleAsString} as double, try removing thousand separators (if any)");
            }
        }
    
        return result;
    }
    

    Works as expected with:

    • 1.1
    • 1,1
    • 1,000,000,000
    • 1.000.000.000
    • 1,000,000,000.99
    • 1.000.000.000,99
    • 5,000,111.3
    • 5.000.111,3
    • 0.99,000,111,88
    • 0,99.000.111.88

    No default conversion is implemented, so it would fail trying to parse 1.3,14, 1,3.14 or similar cases.

提交回复
热议问题