It turns out that:
>>> round(3.5)
4
While:
>>> round(2.5)
2
That is, when a number ends in .5 it sometimes rounds up (as it should) and sometimes rounds down.
Why is this happening? How can I force Python to round in a certain way?
This is a fork of the question How to round "correctly" in python? , because a topic arises that I consider relevant but that is not essential for the author. In order not to spoil his question, I create a new one .
Python 3 uses bankers rounding , that is, the banker's rounding, which consists of rounding
.5
to the nearest even number:This is new in Python 3, as seen in What's new in Python 3.0 :
Namely:
If you wonder why, counterintuitively, then it happens that with decimals this rule doesn't hold...
The builtin page
round()
then reads:Namely:
The idea that rounding .5 up to the next integer is not correct per se . As you can read in this answer to Python 3.x rounding behavior :
And then it indicates that there are five possible types of rounding described in IEEE 754.
If you want to control exactly what rounding you apply, use the module
decimal
with its optionsROUND_HALF_EVEN
,ROUND_HALF_UP
orROUND_HALF_DOWN
( there are more ):