Python3.4 rounds to the nearest even (in the tie-breaker case).
>>> round(1.5)
2
>>> round(2.5)
2
But it only seems to do this when rounding to an integer.
>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9
In the final example above, I would have expected 2.8 as the answer when rounding to the nearest even.
Why is there a discrepancy between the two behaviors?
In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned. This kind of rounding is called rounding to even (or banker's rounding).
To round to the nearest whole number in Python, you can use the round() method. You should not specify a number of decimal places to which your number should be rounded. Our Python code returns: 24. The round() function is usually used with floating-point numbers, which include decimal places.
Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.
Floating point numbers are only approximations; 2.85 cannot be represented exactly:
>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'
It is slightly over 2.85.
0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).
The round()
function documents this explicitly:
Note: The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.68
. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
Martijn got it exactly right. If you want an int-rounder to round to the nearest even, then I would go with this:
def myRound(n):
answer = round(n)
if not answer%2:
return answer
if abs(answer+1-n) < abs(answer-1-n):
return answer + 1
else:
return answer - 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With