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

前端 未结 19 1293
孤街浪徒
孤街浪徒 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:03

    I think it is the best answer:

    public static double StringToDouble(string toDouble)
    {
        toDouble = toDouble.Replace(",", "."); //Replace every comma with dot
    
        //Count dots in toDouble, and if there is more than one dot, throw an exception.
        //Value such as "123.123.123" can't be converted to double
        int dotCount = 0;
        foreach (char c in toDouble) if (c == '.') dotCount++; //Increments dotCount for each dot in toDouble
        if (dotCount > 1) throw new Exception(); //If in toDouble is more than one dot, it means that toCount is not a double
    
        string left = toDouble.Split('.')[0]; //Everything before the dot
        string right = toDouble.Split('.')[1]; //Everything after the dot
    
        int iLeft = int.Parse(left); //Convert strings to ints
        int iRight = int.Parse(right);
    
        //We must use Math.Pow() instead of ^
        double d = iLeft + (iRight * Math.Pow(10, -(right.Length)));
        return d;
    }
    

提交回复
热议问题