What am I missing in understanding round() function?

210 views Asked by At

I was looking at the online doc for round() function in python, which says,

round(number[, ndigits])

....The return value is an integer if called with one argument, otherwise of the same type as number.

So, I wrote the below code.

x = round(32.7)
print 'x is now : ', x
print str(type(x))
print type(x).__name__

Let me explain the last two prints I used in above snippet.

  1. The second print is through trial-and-error method. (Today is my Day 1 for Python)
  2. The third print is added referring to this answer.

Surprisingly, the current output is

x is now : 33.0
<type 'float'>
float

I was expecting

x is now : 33
<type 'int'>
int

I'm out of ideas. What am I missing?

P.S. For anybody interested, a LIVE VERSION

2

There are 2 answers

4
wim On BEST ANSWER

In python 2.x, round always returns a float.

Judging by the syntax of your print statements, you're on python 2.x.

2
yogeswaran palaniappan On

Instead of using round...!try this because round function is to round-off the float values..

However round and type-casting to int both do same work @ background

Hope this helps..!!

x = int(32.7)
print 'x is now :',x
print str(type(x))
print type(x).__name__

or

y=32.7
x=int(y)
print 'x is now :',x
print str(type(x))
print type(x).__name__