Truncate decimal places without rounding in C#
Truncation of numerical values to specified decimal places is crucial in various programming scenarios. Let's consider a situation where we need to truncate the value 3.4679 to 3.46 without rounding it.
A common approach is to use the Math.Round()
function with a specific rounding mode. However, as the provided code shows, using MidpointRounding.ToEven
or MidpointRounding.AwayFromZero
results in 3.47 because of rounding.
A more precise way is to use mathematical operations to truncate the value:
<code class="language-csharp">value = Math.Truncate(100 * value) / 100;</code>
This method truncates the value by multiplying it by 100, then using Math.Truncate()
to remove any decimals, and finally dividing by 100 to restore the original proportions. It effectively throws away decimal places without rounding.
Note:
Please note that fractions like 3.4679 cannot be represented exactly in floating point notation, which may cause slightly different results. For high-precision representation, consider using decimal types instead of floating point numbers.
The above is the detailed content of How to Truncate, Not Round, Decimal Places in C#?. For more information, please follow other related articles on the PHP Chinese website!