Home > Backend Development > C++ > How to Truncate, Not Round, Double Values to a Specific Number of Decimal Places in C#?

How to Truncate, Not Round, Double Values to a Specific Number of Decimal Places in C#?

Mary-Kate Olsen
Release: 2024-12-27 12:15:11
Original
1015 people have browsed it

How to Truncate, Not Round, Double Values to a Specific Number of Decimal Places in C#?

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:

  1. Truncate the double value using Math.Truncate():
double myDoubleValue = 50.947563;
double x = Math.Truncate(myDoubleValue * 100) / 100;
Copy after login

This operation multiplies the value by 100, truncates it to remove decimal places, and then divides it by 100 to restore the original scale.

  1. Format the truncated value using NumberFormatInfo.CurrentInfo:
string s = x.ToString("N2", NumberFormatInfo.CurrentInfo);
Copy after login

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!

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