Why does round(5/2) return 2?

3.3k Views Asked by At

Using python 3.4.3,

round(5/2) # 2

Shouldn't it return 3?

I tried using python 2 and it gave me the correct result

round(5.0/2) # 3

How can I achieve a correct rounding of floats?

3

There are 3 best solutions below

0
On BEST ANSWER

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

Quoting the documentation for the round function. Hope this helps :)

On a side note, I would suggest always read the doc when you face this kind of question (haha)

1
On

Rounding toward even is correct behavior for Python 3. According to the Python 3 documentation for round():

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

Since 2.5 is equally close to 2 and 3, it rounds down to 2.

In Python 2, the docs for round() state:

...if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0)

Since 2.5 is equally close to 2 and 3, it rounds up to 3 (away from zero).

If you want to control how numbers round, the best way to do it might be the way I learned to round numbers back in my Applesoft BASIC days:

10 X = 5
15 PRINT "ROUND(" X "/2) = " (INT((X/2)+0.5))
20 X = 4.99
25 PRINT "ROUND(" X "/2) = " (INT((X/2)+0.5))

Umm...make that:

>>> x = 5 / 2
>>> print(x)
2.5
>>> y = int(x + 0.5)
>>> print(y)
3
>>> x = 4.99 / 2
>>> print(x)
2.495
>>> y = int(x + 0.5)
>>> print(y)
2
>>>
0
On

From doc

round(number[, ndigits]) -> number Round a number to a given precision in decimal digits (default 0 digits).This returns an int when called with one argument, otherwise the same type as the number. ndigits may be negative.

So

>>>round(5/2)
2
>>>round(5.0/2, 1)
2.5