Rounding Off
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--
Inference:
5 at 2nd decimal place is rounded to 1 if first decimal places is non-zero else zero
Why?
How are decimal maintained by .net
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Sam112 pointsPosted Jul 31, 2007, 2:22 AM EDT
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
Hope this helps,
Sam
1 short reply
vaibhav kadian5 pointsPosted Jul 31, 2007, 2:44 AM EDT