Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up and down by Math Round() [duplicate]

Tags:

c#

math

rounding

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?

like image 917
Drakoo Avatar asked Jan 28 '23 03:01

Drakoo


1 Answers

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

like image 176
AliJP Avatar answered Feb 06 '23 12:02

AliJP