Search code examples
c#mathrounding

Truncate Two decimal places without rounding


Lets say I have a value of 3.4679 and want 3.46, how can I truncate that to two decimal places 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

  • value = Math.Truncate(100 * value) / 100;
    

    Beware that fractions like these cannot be accurately represented in floating point.