Convert string to decimal, keeping fractions

后端 未结 11 1360
走了就别回头了
走了就别回头了 2020-11-28 13:31

I am trying to convert 1200.00 to decimal, but Decimal.Parse() removes .00. I\'ve tried some different methods, but it al

11条回答
  •  半阙折子戏
    2020-11-28 13:47

    You can try calling this method in you program:

    static double string_double(string s)
        {
            double temp = 0;
            double dtemp = 0;
            int b = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == '.')
                {
                    i++;
                    while (i < s.Length)
                    {
                        dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
                        i++;
                        b++;
                    }
                    temp = temp + (dtemp * Math.Pow(10, -b));
                    return temp;
                }
                else
                {
                    temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
                }
            }
            return -1; //if somehow failed
        }
    

    Example:

    string s = "12.3";
    double d = string_double (s);        //d = 12.3 
    

提交回复
热议问题