 # Rounding in .NET

I was working through a Pluralsight course a few days ago, and came across a little snippet discussing how Math.Round actually performs it’s rounding calculation. As I was taught in school by default you round up. For example I would have thought that the following test would pass:

``````// Arrange
var expected = 10;
var input = 9.5;

// Act
var actual = Math.Round(input);

// Assert
Assert.AreEqual(expected, actual);``````

The above test passes, because the expected and actual values are equal to 10. Meaning that 9.5 does in fact round up to 10. So does the following test pass?

``````// Arrange
var expected = 9;
var input = 8.5;

// Act
var actual = Math.Round(input);

// Assert
Assert.AreEqual(expected, actual);``````

If you thought that test would pass, you'd be wrong!

The test doesn't pass because .NET uses “Bankers Rounding” by default. In Bankers Rounding midpoint results round to the nearest even number. So in the above test, the “actual” value is equal to 8!

However, you can control the rounding by using the MidpointRounding enumeration, as follows:

``````// Arrange
var expected = 9;
var input = 8.5;

// Act
var actual = Math.Round(input, MidpointRounding.AwayFromZero);

// Assert - Is actual equal to 9?
Assert.AreEqual(expected, actual);``````

So the above test passes because the value of 8.5 has been rounded up to 9.

So the next time you're using rounding, keep this important little gotcha in mind... Sydney, Australia
Experienced developer/consultant. Loves all things development, technology, gadgets, football and running.