When working in .Net, you might wonder why it doesn't round off numbers the same way you learned in school.
.Net uses what is called "Bankers rounding" which means that in the event of a tie (e.g. 2,5) it will round towards the nearest even number, so
Math.Round(2.5) --> 2
Math.Round(1.5) --> 2
This is due to the fact that consistently rounding up (as you might remember from your schooldays) will result in a strictly increasing rounding error for all "tied" numbers (.5). Since banks typically have quite a few transactions each day, the term "strictly increasing rounding error" sounds bad to them.
why does .Net provide this rounding as default? -dont know dont care
what do we do about it? - do know do care:
define and use MidpointRounding.AwayFromZero as parameter in a custom util method.
public enum MidpointRounding
{
ToEven, AwayFromZero
}
public class Util
{
public static double Round( double number, int digits, MidpointRounding roundingType)
{
if (roundingType == MidpointRounding.AwayFromZero)
{
double multiplyValue = Math.Pow( 10, digits );
double dRound = Math.Floor(((number*2*multiplyValue)+1)/2)/multiplyValue;
return dRound;
}
else
{
return Math.Round(number,digits);
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment