Rounding error in Python with non-odd number? [duplicate]

Python 3.x, in contrast to Python 2.x, uses Banker’s rounding for the round() function.

This is the documented behaviour:

[I]f two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

Since floating point numbers by their very nature are only approximations, it shouldn’t matter too much how “exact” half-integers are treated – there could always be rounding errors in the preceding calculations anyway.

Edit: To get the old rounding behaviour, you could use

def my_round(x):
    return int(x + math.copysign(0.5, x))

Leave a Comment