C# Tips

C# Tip Article

C# round up issue in Math.Round()

To round up a number, C# uses a .NET method called Math.Round(). For example, Math.Round(1.5) returns 2 and Math.Round(3.5) return 4, as we expect.

But what is the result of Math.Round(2,5) or Math.Round(4.5)? You would guess the result is 3 or 5.
No, actual result is 2 or 4, surprisingly.

var a = Math.Round(1.5);
var b = Math.Round(2.5);

Console.WriteLine(a); // 2
Console.WriteLine(b); // 2

Math.Round() method always returns the integer nearest input number. And if the fractional component of input number is halfway between two integers, one of which is even and the other odd, then the even number is returned. This is so-called banker's rounding and its behavior follows IEEE Standard 754.

So how can we write a correct(?) roundup? We want to round up 1.5 to 2, and 2.5 to 3.
Here is a small function that does that.

double RoundUp(double x)
	return Math.Floor(x + 0.5);

// Using the method
var a = RoundUp(1.5);  // 2
var b = RoundUp(2.5);  // 3