Rounding in .NET: A fair warning
Everybody uses the same rounding they learned in school. Only Siths deal in absolutes, as they say, but this is really really basic: .0, .1, .2, .3, .4 round down, and .5, .6, .7, .8, .9 round up. We’ve all learned this in school.
.NET Framework designers have taken it upon themselves to make fools of us all by defaulting the rounding algorithm (used by
Math.Round) to something called “Banker’s rounding.” It behaves the same, except for .5, which will round to the nearest even integer. 2.5 rounds down to 2, 3.5 rounds up to 4. This was done so as to distribute .5 evenly up or down. Or a better explanation might be…
And hey, it’s not some totally made up thing if it’s got its own IEEE rule, right?
Fine, enough ranting. Here’s the way to round a number for the rest of us humans:
Math.Round(2.5, MidpointRounding.AwayFromZero); //Equals 3
The default is:
Math.Round(2.5, MidpointRounding.ToEven); //Equivalent to Math.Round(2.5); Equals 2