4

I have something like this:

double d1 = Math.Round(88.5, 0); // result 88
double d2 = Math.Round(89.5, 0); // result 90

Why is Math.Round() rounding even numbers down and odd numbers up?

Drakoo
  • 307
  • 1
  • 3
  • 15
  • 6
    It's using *banker's rounding*. Note that this is exactly [as documented](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.7.1#System_Math_Round_System_Double_): "If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned." – Jon Skeet May 14 '18 at 07:10
  • 1
    Show this ticket : https://stackoverflow.com/questions/977796/why-does-math-round2-5-return-2-instead-of-3 – Oilid May 14 '18 at 07:11

1 Answers1

8

You can use MidpointRounding parameter in Math.Round.
When you're using Math.Round, one of its overload, is an overload which takes 2 parameters, the first one is your value and the second one is an enum of type MidpointRounding.

Consider code below:

Math.Round(88.5, MidpointRounding.AwayFromZero) // The result is 89
Math.Round(88.5, MidpointRounding.ToEven) // The result is 88

Here is the MSDN documentation about Math.Round with MidpointRounding:
https://msdn.microsoft.com/en-us/library/ef48waz8(v=vs.110).aspx
And here is the documentation about the MidpointRounding:
https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx

AliJP
  • 668
  • 1
  • 4
  • 16