Truncating Double Values with No Rounding in C#
When converting a double-precision floating-point number to a string in C#, you may encounter the need to format it with a specific number of decimal places. However, using String.Format("{0:0.00}") can lead to rounding, which is undesirable for certain scenarios where you want exact truncation.
To address this issue, use a combination of Math.Truncate() and NumberFormatInfo.CurrentInfo to achieve truncation without rounding and maintain culture-sensitive formatting.
Solution:
double myDoubleValue = 50.947563; double x = Math.Truncate(myDoubleValue * 100) / 100;
This operation multiplies the value by 100, truncates it to remove decimal places, and then divides it by 100 to restore the original scale.
string s = x.ToString("N2", NumberFormatInfo.CurrentInfo);
This format specifier uses the "N" format string, which includes currency formatting with a trailing percentage sign. NumberFormatInfo.CurrentInfo ensures that the formatting follows the current culture settings.
Result:
Using the above method, you will obtain a string representation of the double value with exactly two decimal places without any rounding. For example, the value 50.947563 will be truncated to 50.94 without rounding up to 50.95.
The above is the detailed content of How to Truncate, Not Round, Double Values to a Specific Number of Decimal Places in C#?. For more information, please follow other related articles on the PHP Chinese website!