Double to string conversion without scientific notation

前端 未结 17 1468
無奈伤痛
無奈伤痛 2020-11-22 15:33

How to convert a double into a floating-point string representation without scientific notation in the .NET Framework?

\"Small\" samples (effective numbers may be of

17条回答
  •  执念已碎
    2020-11-22 15:57

    The obligatory Logarithm-based solution. Note that this solution, because it involves doing math, may reduce the accuracy of your number a little bit. Not heavily tested.

    private static string DoubleToLongString(double x)
    {
        int shift = (int)Math.Log10(x);
        if (Math.Abs(shift) <= 2)
        {
            return x.ToString();
        }
    
        if (shift < 0)
        {
            double y = x * Math.Pow(10, -shift);
            return "0.".PadRight(-shift + 2, '0') + y.ToString().Substring(2);
        }
        else
        {
            double y = x * Math.Pow(10, 2 - shift);
            return y + "".PadRight(shift - 2, '0');
        }
    }
    

    Edit: If the decimal point crosses non-zero part of the number, this algorithm will fail miserably. I tried for simple and went too far.

提交回复
热议问题