Rounding Error · 29 September, 09:45 AM

Quick quiz: what does the following code print?

System.Out.WriteLine(Math.Round(0.5));

If you answered “1”, that’s incorrect. There is a reason for this, it’s called “banker’s rounding”. It’s nicely documented in the MSDN docs for the function. It’s also completely deceptive to the unwary programmer. We’re all trained in elementary math to think that Math.Round(0.5) returns 1. Banker’s rounding is probably in general a good idea when working with a lot of numbers, but in the simple case where you want to round one number, away from zero is the expected behavior. As of .NET 2.0, there’s an option to do this, but it’s still not the default.

The one lesson I got from this is that you can’t assume anything about your code. It just reinforced the need for really, really granular unit tests.

— Gordon Weakliem

---

Comment

Commenting is closed for this article.