Jibin
Jibin

Reputation: 3102

Why this strange behaviour of 'round' built in.(python 2.6)

Why So ?

>>> round(2/3)

0.0

>>> round(0.66666666666666666666666666666667)

1.0

>>> round(2.0/3)

1.0

Upvotes: 1

Views: 1118

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308001

That's not strange behaviour from round():

Try this:

>>> 2/3
0

Using / with two integer values will do an integer division. So the argument to round() is already 0, which makes round() return 0.

Update: as @Mark noted in the comment, this behaviour changed in Python 3: 2/3 will do a floating point division as 2.0/3 does in Python 2. 2//3 can be used to get integer division behaviour on both versions).

Your last example works, because 2.0 is not integer, so 2.0/3 will do a "propper" floating point division:

>>> 2.0/3
0.6666666666666666

Upvotes: 16

Related Questions