Tuesday, July 31, 2007

Rounding Off decimal places

what is the output of the following statements :

Console.WriteLine(decimal.Round(Convert.ToDecimal("0.05"), 1)); --0.0--
Console.WriteLine(decimal.Round(Convert.ToDecimal("0.15"), 1)); --0.2--

5 at 2nd decimal place is rounded to 1 if first decimal places is non-zero else zero
Why?



Explanation
The decimal.Round version that take 2 parameters
rounds midpoints to the even number (Banker's Rounding)
rather than rounding them away from zero

i.e
decimal.Round(0.05, 1); // 0.0
decimal.Round(0.15, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.25, 1); // 0.2
decimal.Round(0.35, 1); // 0.4
etc.

To get 'normal' rounding (midpoints are rounded away from zero)
you can use a overloaded version of the decimal.Round
method that takes a thrid parameter, which
specifies how to treat midpoints:

ie
decimal.Round(0.05, 1, MidpointRounding.ToEvent); // 0.0 Banker's Rounding

decimal.Round(0.05, 1, MidpointRounding.AwayFromZero); // 0.1

No comments: