Matthew Cox Team : Web Development Tags : Web Development

.net Rounding

Matthew Cox Team : Web Development Tags : Web Development

While working on some older code this morning I found this little doozy:

My first instinct was just to delete it and replace all references with Math.Round(), but I know we usually don’t reinvent the wheel unless we find it to be a bit square. So I investigated further. I know Math.Round() has an overload that accepts and enum that specifies which type of rounding to use and I always assumed the default would be ‘symmetric arithmetic rounding’. In other words I assumed that numbers ending in .5 would always round up. However, looking at the enum told a very different story.

It seems the default is to use ‘bankers rounding’ which rounds values ending in .5 towards even numbers so both 1.5 and 2.5 would round to 2. I generally prefer this method because over a normally distributed set of numbers it will eliminate the bias that would be added by always rounding up, however this was not the behaviour I was expecting. So to put a long story short, I had to replace the method with Math.Round(amount, 0, MidPointRounding.AwayFromZero), instead of just Math.Round(amount) and learned something in the process.