1

I understand that 2.675 rounds to 2.67 in python2. I understand WHY it rounds down instead of rounding up.

However, there is no case that I can think of where this is the desired outcome.

So, is there a better way to deal with this than defining my own round function?

def r2(n, d):
  return round(n * 10**d) / 10**d

Is there a case where this will fail?

Also, how is this not considered a bug?

Brian Postow
  • 11,709
  • 17
  • 81
  • 125
  • 2
    If you want decimal math, use `decimal.Decimal`. Floats are binary. – user2357112 Aug 09 '17 at 16:20
  • 4
    Also, your `r2` is broken - see `r2(0.575, 2)` - and there was never any reason to expect it to work better than the default `round` in the first place. If you expected it to work, you might not really understand why `round` behaves the way it does. – user2357112 Aug 09 '17 at 16:27
  • I had a feeling that there was no way that this would work... – Brian Postow Aug 09 '17 at 19:00
  • @BrianPostow: Making it "work" would involve having `round` inspect the actual float value it receives, somehow deduce from that the original decimal value that the user wanted to round, and then round _that_ decimal value. That "somehow deduce" bit quickly becomes a messy heuristic that "works" in some situations but not others, ultimately producing more user confusion that it solves (e.g., perhaps rounding `2.675` now "works", but rounding `2.0 + 0.675` doesn't). Better to have a `round` function with clear, well-defined, non-magic non-DWIMmy behaviour. If this matters to you, use `decimal`. – Mark Dickinson Aug 10 '17 at 11:50
  • BTW, the Python version is mostly irrelevant here: making the relatively safe assumption of IEEE 754 floats, both Python 2.7 and Python 3.x with x >= 2 will return `2.67` from `round(2.675, 2)`. (The history of `round` prior to Python 2.7 is a bit more muddled.) – Mark Dickinson Aug 10 '17 at 12:02

0 Answers0