Why does round (5/2) return 2?

Using python 3.4.3,

round(5/2) # 2

Should it return 3?

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

round(5.0/2) # 3

How can I achieve the correct rounding of the floats?

+4
source share
3 answers

if two multiples are equally close, rounding is performed in the even direction (for example, both round (0.5) and round (-0.5) are 0, and round (1.5) is 2).

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

On a side note, I would suggest to always read the document when you are confronted with this question ( haha )

+4
source

Python 3. Python 3 round():

... , (, , (0,5), (-0,5) 0, (1.5) 2)

2.5 2 3, 2.

Python 2 docs round():

... , 0 (, , round (0.5) 1.0 round (-0.5) -1.0)

2.5 2 3, 3 ( ).

, , , Applesoft BASIC:

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

... :

>>> 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
>>>
+4

doc

round (number [, ndigits]) β†’ number Round the number to the specified precision in decimal digits (0 digits by default). This returns an int when called with one argument, otherwise the same type as the number. ndigits can be negative.

So,

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

All Articles