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; } }
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
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!