-2

In Python 3.5, I'm seeing the following rounding behavior:

>>> round(7.55, 1)
7.5 # expected to round up to 7.6

>>> round(7.45, 1)
7.5 # this is fine

Maybe my intuition is incorrect, but I expect the hundreths of 5 in 7.55 to round upwards to 7.6. The standard Python 3 behavior is not what matches my data's expectation; I clearly need something beyond the standard round method to achieve this goal. Is there a way to get this behavior?

jumbopap
  • 3,969
  • 5
  • 27
  • 47
  • This should definitely be as a result of precision. – Rohit Jain Aug 14 '16 at 18:47
  • I think using numpy's round() method could help you to achieve the behavior you want. Given that the answers that people here have given are correct, that's the expected behavior in Python default round function. – d4vsanchez Aug 14 '16 at 18:56
  • Why was this closed? This question is not a duplicate. I am expecting certain behavior and not getting it with the standard `round` function. I am asking how to get that behavior. – jumbopap Aug 14 '16 at 19:01
  • It *is* a duplicate, but not of the linked question; the linked question is all about Python's behaviour in exact halfway cases, but the numbers you give are *not* exact halfway cases (because of the usual what-you-see-is-not-what-you-get nature of binary floating-point). – Mark Dickinson Aug 14 '16 at 20:41
  • 1
    Better duplicate: http://stackoverflow.com/questions/34620633/how-does-rounding-in-python-work – Mark Dickinson Aug 14 '16 at 20:44

2 Answers2

4

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

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

shanu khera
  • 170
  • 1
  • 12
2

Besides the issue with precision be also aware of the even/odd behaviour of round in this context:

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; 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). The return value is an integer if called with one argument, otherwise of the same type as number.

ChE
  • 88
  • 7