-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?

asked Aug 14, 2016 at 18:44
5
  • This should definitely be as a result of precision. Commented Aug 14, 2016 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. Commented Aug 14, 2016 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. Commented Aug 14, 2016 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). Commented Aug 14, 2016 at 20:41
  • 1
    Better duplicate: stackoverflow.com/questions/34620633/… Commented Aug 14, 2016 at 20:44

2 Answers 2

3

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.

answered Aug 14, 2016 at 18:51
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Aug 14, 2016 at 18:48

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.