Formatting Doubles in C#
When outputting doubles, C# automatically rounds them to 15 significant digits before applying any formatting. This can lead to discrepancies between the formatted output and the actual value of the double.
Problem with String.Format:
The String.Format method in C# only affects the display of the formatted number. It does not adjust the precision of the underlying double value. As a result, String.Format("{0:F20}", i) will display 20 decimal places, but the actual value of the double may still have been rounded to 15 decimal places internally.
Example:
Consider the following code:
double i = 10 * 0.69; Console.WriteLine(String.Format(" {0:F20}", i));
The output will be 6.90000000000000000000 , even though the actual value of i is closer to 6.89999999999999946709.
Solution:
To output the exact decimal value of a double, you can use Jon Skeet's DoubleConverter class. This class has a ToExactString method that returns the exact decimal representation of a double. You can then format the string as needed.
For example:
double i = 10 * 0.69; Console.WriteLine(DoubleConverter.ToExactString(i));
This will output 6.89999999999999946709294817992486059665679931640625 , which is the exact decimal representation of i.
The above is the detailed content of How Can I Accurately Output the Exact Decimal Value of a Double in C#?. For more information, please follow other related articles on the PHP Chinese website!