Double to string conversion without scientific notation

前端 未结 17 1463
無奈伤痛
無奈伤痛 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 16:02

    For a general-purpose¹ solution you need to preserve 339 places:

    doubleValue.ToString("0." + new string('#', 339))

    The maximum number of non-zero decimal digits is 16. 15 are on the right side of the decimal point. The exponent can move those 15 digits a maximum of 324 places to the right. (See the range and precision.)

    It works for double.Epsilon, double.MinValue, double.MaxValue, and anything in between.

    The performance will be much greater than the regex/string manipulation solutions since all formatting and string work is done in one pass by unmanaged CLR code. Also, the code is much simpler to prove correct.

    For ease of use and even better performance, make it a constant:

    public static class FormatStrings
    {
        public const string DoubleFixedPoint = "0.###################################################################################################################################################################################################################################################################################################################################################";
    }
    

    ¹ Update: I mistakenly said that this was also a lossless solution. In fact it is not, since ToString does its normal display rounding for all formats except r. Live example. Thanks, @Loathing! Please see Lothing’s answer if you need the ability to roundtrip in fixed point notation (i.e, if you’re using .ToString("r") today).

提交回复
热议问题