Sunday, October 23, 2011

Round issue in c#

Today one of my friend asked me that he has some problems while rounding value to 2 decimal places and he was trying to round "2.145" up to 2 decimal places , he used Math.Round() funciton but it was giving output as 2.14 then I told him to use Math.Round(value, 2, MidpointRounding.AwayFromZero)) and he used it and was very happy that his issue solved .
But later I came to know that there are still issues present with
Math.Round(value, 2, MidpointRounding.AwayFromZero)) as mentioned on msdn at
that it will round 0.145 to 0.14 instead of 0.15 and rounding 2.135 to 2.13 instead of 2.14 becuae of loss of precision.
I found the two solutions for the above problem

Solution 1:
Convert double to decimal
Math.Round((decimal(2.135), 2, MidpointRounding.AwayFromZero) it would show 2.14 and
Math.Round((decimal)0.145, 2, MidpointRounding.AwayFromZero) it would show 0.15

Solution 2:
use Math.Ceiling
System.Math.Ceiling(2.135 * 100) / 100 it would show 2.14
System.Math.Ceiling(0.145 * 100) / 100 it would show 0.15

1 comment: