Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round returning a rounded up for odd values but rounds down for even

Tags:

c#

math

rounding

I am trying to found a float using math round I found the following

0.5 --> 0
1.5 --> 2
2.5 --> 2
3.5 --> 4

and so on. I believe this is due to floating point error, but not quite sure how. How can I get around this so even numbers round properly?

like image 219
Kuzon Avatar asked Dec 02 '22 15:12

Kuzon


1 Answers

From documentation;

The integer nearest a. 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. Note that this method returns a Double instead of an integral type.

Math.Round method has some overloads that takes MidpointRounding as a parameter which you can specify the rounding value if it is midway between two numbers.

AwayFromZero 

When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

ToEven

When a number is halfway between two others, it is rounded toward the nearest even number.

like image 152
Soner Gönül Avatar answered Dec 15 '22 12:12

Soner Gönül