0
>>> print('result:%9.2f' % 1111.225)
result:  1111.22
>>> print('result:%9.2f' % 11111.225)
result: 11111.23
>>> print('result:%9.2f' % 111.225)
result:   111.22
>>> print('result:%9.2f' % 11.225)
result:    11.22
>>> print('result:%9.2f' % 1.225)
result:     1.23

In the above example, you can see that 111.225 and 11.225 are rounded downwards, while the others are rounded upwards. As they all end on .225, one would expect them all to be rounded upwards to .23. Why does the rounding of the numbers differ?

The_spider
  • 1,202
  • 1
  • 8
  • 18
张玉科
  • 1
  • 1
  • [This answer](https://stackoverflow.com/a/588014/477878) goes into more detail, but basically floating point math on a computer does not in general represent _exact_ numbers, which means 11.225 in your code may be stored as something slightly less than 11.225 in reality and round down while 1.225 may be stored as something slightly more than 1.225 in reality and round up. – Joachim Isaksson Dec 27 '22 at 07:25
  • Try for example `n= 11.225; print('result:%9.22f' % n)` and the same with 1.225 to see a bit more how the values are actually stored. – Joachim Isaksson Dec 27 '22 at 07:37

0 Answers0