In Python 3.5, I'm seeing the following rounding behavior:
>>> round(7.55, 1)
7.5 # expected to round up to 7.6
>>> round(7.45, 1)
7.5 # this is fine
Maybe my intuition is incorrect, but I expect the hundreths of 5 in 7.55 to round upwards to 7.6. The standard Python 3 behavior is not what matches my data's expectation; I clearly need something beyond the standard round method to achieve this goal. Is there a way to get this behavior?
2 Answers 2
https://docs.python.org/2/library/functions.html#round
Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.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.
Comments
Besides the issue with precision be also aware of the even/odd behaviour of round in this context:
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if 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). The return value is an integer if called with one argument, otherwise of the same type as number.
roundfunction. I am asking how to get that behavior.