Home > Backend Development > C++ > How Can I Accurately Output the Exact Decimal Value of a Double in C#?

How Can I Accurately Output the Exact Decimal Value of a Double in C#?

Mary-Kate Olsen
Release: 2025-01-05 16:57:41
Original
184 people have browsed it

How Can I Accurately Output the Exact Decimal Value of a Double in C#?

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));
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template