1

What am I doing wrong?

>>> round(2.5), round(0.25, 1), round(0.025, 2)
(3.0, 0.3, 0.03)

>>> round(4.5), round(0.45, 1), round(0.045, 2)
(5.0, 0.5, 0.04)

Why is 0.025 rounded to 0.03 (up), but 0.045 to 0.04 (down)?

Using Python2.7 on OSX:

Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Martin Tóth
  • 1,747
  • 3
  • 24
  • 35
  • 2
    @DavidG: The other question actually covers both by side-effect, and [this answer](https://stackoverflow.com/a/24534369/364696) specifically mentions the issue with inexact binary floating point representations meaning that `float` rounding is often not intuitive (because the final `5` ends up actually being `499999999995345535` or `50000000000000234234` or the like, so the rounding mode for exactly in-between values doesn't matter; it's not actually in between). – ShadowRanger Nov 03 '17 at 10:29
  • Yes you're right. I thought the problem was floating point representation, I just didn't read the answers all the way down! – DavidG Nov 03 '17 at 10:30
  • 1
    @MartinTóth: You use the `decimal` module; it's not possible with `float`, because there is no such thing as `0.045` in `float`, there is just something roughly equal to `0.04499999999999999833466546306227` (where `0.045` is a convenient shorthand). – ShadowRanger Nov 03 '17 at 10:33
  • Right, thank you! ```Decimal('0.045').quantize(Decimal('0.01'), ROUND_HALF_UP)``` results in ```Decimal('0.05')``` – Martin Tóth Nov 03 '17 at 10:35

0 Answers0