Home > Backend Development > C++ > How Can I Accurately Format Doubles in C# to Match Specified Precision?

How Can I Accurately Format Doubles in C# to Match Specified Precision?

Barbara Streisand
Release: 2025-01-04 11:40:34
Original
1007 people have browsed it

How Can I Accurately Format Doubles in C# to Match Specified Precision?

Formatting Doubles for Output in C

In C#, the default behavior for formatting doubles is to round the value to 15 significant decimal digits before applying the specified precision. This can lead to unexpected results, especially when dealing with values that have a small difference in precision.

To accurately format doubles and ensure that the requested precision is respected, one can utilize the DoubleConverter class provided by Jon Skeet. The ToExactString() method in this class returns the exact decimal value of a double. To incorporate rounding to a specified precision, the method can be modified as follows:

public static string ToRoundedExactString(double value, int precision)
{
    string exactString = ToExactString(value);
    int decimalIndex = exactString.IndexOf('.');
    if (decimalIndex == -1)
    {
        return exactString;
    }

    int decimalCount = exactString.Length - (decimalIndex + 1);
    if (decimalCount > precision)
    {
        exactString = exactString.Substring(0, decimalIndex + 1 + precision);
        double roundedValue = Double.Parse(exactString);
        return roundedValue.ToString();
    }
    else
    {
        return exactString;
    }
}
Copy after login

Using this modified method, the following code will produce the output that matches the precision specified in the format specifiers:

double i = 10 * 0.69;
Console.WriteLine(DoubleConverter.ToRoundedExactString(i, 20));
Console.WriteLine(DoubleConverter.ToRoundedExactString(6.9 - i, 20));
Console.WriteLine(DoubleConverter.ToRoundedExactString(6.9, 20));

// 6.89999999999999946709
// 0.00000000000000088818
// 6.90000000000000035527
Copy after login

The above is the detailed content of How Can I Accurately Format Doubles in C# to Match Specified Precision?. 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