-2

Yes, I know about floats and I have read the replies to other similar questions (including the link about what every programmer should know about floating points).

I understand that float calculations might go wrong, but I was surprised that the following actually happened:

Python 3.9.6 (default, Jun 30 2021, 10:22:16) 
>>> round(2.45, 1)
2.5  # correct
>>> round(2.25, 1)
2.2  # wrong
>>> round(3.25, 1)
3.2  # wrong

I was (still am) bitten by this an I am surprised that this super simple thing does not work in Python.

Is this expected behaviour? Do I really need the Decimals package to deal with these simple calculations?

Patrick
  • 303
  • 4
  • 13
  • 2
    From the [docs](https://docs.python.org/3/library/functions.html#round): if two multiples are equally close, rounding is done toward the even choice –  Sep 01 '21 at 12:47
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – BTables Sep 01 '21 at 12:48
  • 1
    @Sujay: note that that logic does *not* apply to the first case, though (rounding `2.45`). The dupe is a bit misleading - there are two separate effects here - the choice of rounding mode (round ties to even), *and* the inability of binary floating-point to represent values like `2.45` exactly. Note that `2.25` and `3.25` are special here in that they're represented exactly, so the round-ties-to-even rule applies. But `2.45` is not represented exactly: it's not a tie, and the round-ties-to-even rule isn't relevant. It rounds up because it's closer to `2.5` than to `2.4`. – Mark Dickinson Sep 01 '21 at 13:30

1 Answers1

1

[...] 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).

https://docs.python.org/3/library/functions.html#round

Thomas
  • 8,357
  • 15
  • 45
  • 81