tags:

views:

238

answers:

4

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));
}
+11  A: 
value = Math.Truncate(100 * value) / 100;

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

Hans Passant
Use decimal for your values and this answer will work. It is unlikely to always work in any floating point representation.
driis
Perfect, Thanks.
Neil
That makes me wonder whether it should be possible to specify rounding direction in floating point literals. Hmmmm.
Steve314
+2  A: 

would this work for you?

Console.Write(((int)(3.4679999999*100))/100.0);
John Boker
A: 

Would ((long)(3.4679 * 100)) / 100.0 give what you want?

Frank
A: 

((long)(3.4679 * 100)) / 100.0 - This is GREAT!! it works for me! i've been looking for a way to do this and it finally works!!! thanks a bunch!!

erika