Truncate Two decimal places without rounding
Lets say I have a value of 3.4679 and want 3.46, how can I truncate to two decimal places that without rounding up?
I have tried the following but all three give me 3.47:
void Main()
{
Console.Write(Math.Round(3.4679, 2,MidpointRounding.ToEven));
Console.Write(Math.Round(3.4679, 2,MidpointRounding.AwayFromZero));
Console.Write(Math.Round(3.4679, 2));
}
This returns 3.46, but just seems dirty some how:
void Main()
{
Console.Write(Math.Round(3.46799999999 -.005 , 2));
}
Solution 1:
value = Math.Truncate(100 * value) / 100;
Beware that fractions like these cannot be accurately represented in floating point.
Solution 2:
It would be more useful to have a full function for real-world usage of truncating a decimal in C#. This could be converted to a Decimal extension method pretty easy if you wanted:
public decimal TruncateDecimal(decimal value, int precision)
{
decimal step = (decimal)Math.Pow(10, precision);
decimal tmp = Math.Truncate(step * value);
return tmp / step;
}
If you need VB.NET try this:
Function TruncateDecimal(value As Decimal, precision As Integer) As Decimal
Dim stepper As Decimal = Math.Pow(10, precision)
Dim tmp As Decimal = Math.Truncate(stepper * value)
Return tmp / stepper
End Function
Then use it like so:
decimal result = TruncateDecimal(0.275, 2);
or
Dim result As Decimal = TruncateDecimal(0.275, 2)
Solution 3:
Universal and fast method (without Math.Pow()
/ multiplication) for System.Decimal
:
decimal Truncate(decimal d, byte decimals)
{
decimal r = Math.Round(d, decimals);
if (d > 0 && r > d)
{
return r - new decimal(1, 0, 0, false, decimals);
}
else if (d < 0 && r < d)
{
return r + new decimal(1, 0, 0, false, decimals);
}
return r;
}