See the documentation :
Note The behavior of round() for floats may be unexpected: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68 . This is not a mistake: it is the result of the fact that most decimal fractions cannot be represented exactly as a float. See Floating Point Arithmetic: Problems and Limitations for more information.
If you keep digging (i.e. click this link), you will find an example similar to yours:
The documentation for the built-in round() function states that it rounds to the nearest value, rounding off ties from zero. Since the 2.675 decimal is halfway between 2.67 and 2.68 , you can expect the result here to be (binary approximation) 2.68 . It is not, because when the decimal string 2.675 converted to a binary floating-point number, it is again replaced by a binary approximation whose exact value is
2.67499999999999982236431605997495353221893310546875
Formatting strings will also not fix your problem. The floating point number simply does not persist as you expected:
>>> '{:0.2f}'.format(1.555) '1.55'
This is actually not a βfixβ, but Python has a decimal module that is designed for floating point arithmetic:
>>> from decimal import Decimal >>> n = Decimal('1.555') >>> round(n, 2) Decimal('1.56')
source share