0

According to Banker's rounding, ties goes to even, for example,

round(1.25,1) -> 1.2 round(1.35,1) -> 1.4

But, in case of following rounding,

round(1.15,1) -> 1.1

It should be 1.2, why it is 1.1

Can anyone help.

dar189901
  • 11
  • 1
  • 4
  • Does this answer your question? [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – Sasha Dec 10 '21 at 11:35
  • 1
    https://docs.python.org/3/library/functions.html#round – snakecharmerb Dec 10 '21 at 11:36
  • Dear, my question simply is that banker's rounding behave strangly when it is given round(1.15,1). As, you can see that 1.25 its output is 1.2 (due to ties, choose even, but 1.15 is also ties, so it must be 1.2, rather 1.1) – dar189901 Dec 12 '21 at 11:06

1 Answers1

0

float implementation in python do not allow to save any fraction, so certain are saved as approximations, see decimal built-in module docs for further discussion. python does show it as 1.15 but in reality it is other (close) number which can be saved as float, consider following

print(1.15+1.15+1.15==3.45)  # False
print(1.15+1.15+1.15)  # 3.4499999999999997

You might use decimal.Decimal to prevent float-related problems as follows

import decimal
approx = round(decimal.Decimal("1.15"),1)
print(approx)  # 1.2

Note that you should use str as decimal.Decimal not float.

Daweo
  • 31,313
  • 3
  • 12
  • 25