Exact double-precision float to string conversion in .NET, avoiding scientific notation
Converting a double-precision floating point number to a floating-point string representation in .NET can present challenges, especially when looking for a solution that effectively suppresses scientific notation for both large and small numbers.
One way is to use a custom format string that specifies the desired precision after the decimal point. To accurately represent all possible double-precision floating point values, a large number of numbers are required. A general solution to this requirement is:
<code class="language-csharp">doubleValue.ToString("0." + new string('#', 339))</code>
This format string contains 339 pound characters ('#'), representing the maximum number of non-zero decimal places (15) that can be shifted to the right by the exponent (324 bits).
It is important to note that due to the potential explicit rounding of ToString(), this method provides precision rather than lossless conversion. For lossless round-trip conversion, consider the alternative solution provided by @Loathing.
To improve usability and performance, format strings can be stored as constants:
<code class="language-csharp">public static class FormatStrings { public const string DoubleFixedPoint = "0.###################################################################################################################################################################################################################################################################################################################################################"; }</code>
Using this technique, double-precision floating point numbers can be easily converted into string representations without scientific notation, ensuring accurate display of large and small numbers in applications.
The above is the detailed content of How Can I Precisely Convert Doubles to Strings in .NET Without Scientific Notation?. For more information, please follow other related articles on the PHP Chinese website!