Check if a number is int or float


Question

Here's how I did it:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

Something like that.
Are there any nicer looking ways to do this?

1
160
12/27/2010 7:14:41 PM

Use isinstance.

>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True

So:

>>> if isinstance(x, int):
        print 'x is a int!'

x is a int!

_EDIT:_

As pointed out, in case of long integers, the above won't work. So you need to do:

>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
235
12/27/2010 8:00:49 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon