280

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?

Steinthor.palsson
  • 6,286
  • 13
  • 44
  • 51
  • 10
    The trick is to search on SO for all the other times this question was asked. Each of those will provide a repeat of the same, standard answer. – S.Lott Dec 27 '10 at 19:21
  • 4
    related: [How to check if a float value is a whole number](http://stackoverflow.com/q/21583758/4279). – jfs Oct 19 '14 at 11:47
  • @Wooble: it fails for [larger numbers](http://stackoverflow.com/a/26447472/4279). – jfs Oct 19 '14 at 11:48
  • 2
    `assert isinstance(inNumber, (int, float)), "inNumber is neither int nor float, it is %s" % type(inNumber)` was what I was looking for when I found this question with Google. – Martin Thoma Mar 28 '15 at 13:20
  • 2
    The questions is not particularly well put. Is the OP asking: 1) "What is the intrinsic Python variable type of the variable `somenumber`?" 2) Is `somenumber` a whole number? 3) Is `somenumber` a string that is known to represent a number, but is does it represent an integer or floating point value? Some COUNTER CASES would help respondents suggest a suitable solution. – Dan H Oct 26 '17 at 17:39
  • Solution: https://stackoverflow.com/a/64132078/8321339 – Vishal Gupta Sep 30 '20 at 06:47

19 Answers19

395

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!

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
Neuron
  • 5,141
  • 5
  • 38
  • 59
user225312
  • 126,773
  • 69
  • 172
  • 181
  • wouldn't `issubclass` be more generic? – David Heffernan Dec 27 '10 at 19:26
  • 3
    @David: `issubclass` would be an error, as it works on classes. `isinstance` checks if a given object is an instance of a class *or one of that class's subclasses*, so it's perfectly generic. Methinks that `isinstance(obj, cls)` is equivalent to `issubclass(obj.__class__, cls)` –  Dec 27 '10 at 19:33
  • 8
    This doesn't work for other integer types, for example if `x = 12L`. I know only `int` was asked for, but it's nice to fix other problems before they happen. The most generic is probably `isinstance(x, numbers.Integral)`. – Scott Griffiths Dec 27 '10 at 19:39
  • @delnan Thanks, I wasn't aware that isinstance checked for subclasses. Thinking about it, it seems obvious now that it makes no sense to do anything else. If one wants to check to class identity then one can write `type(obj) is cls`. – David Heffernan Dec 27 '10 at 19:39
  • @Scott: I have no idea about `numbers`, feel free to update the question so that it can help someone in case they end up here searching for it. – user225312 Dec 27 '10 at 19:41
  • @Scott are all built-in integral types in Python subclasses of `numbers.Integral`? – David Heffernan Dec 27 '10 at 19:43
  • @David: `assert isinstance(1, numbers.Integral) and isinstance(1L, numbers.Integral)` (and in Python 3, that's moot because `long` is removed and `int` is always arbitrary-precision). –  Dec 27 '10 at 19:58
  • @David Heffernan: `numbers.Integral` is an Abstract Base Class that allows anyone to write classes that promise to behave as integers. Any built-in type certainly works, but results might be mixed otherwise, for example `numpy.int16` isn't (yet) `Integral`. – Scott Griffiths Dec 27 '10 at 21:24
  • 10
    For Python 2, there is also the direct double check: `isinstance(x, (int, long))`. – Eric O. Lebigot Apr 28 '13 at 13:05
  • 4
    WARNING: bools are instances of integers also. See `isinstance(True, int)` – jtschoonhoven Jul 16 '18 at 22:28
  • Are there still cases for Python3 where `isinstance(somebignumber, int)` returns `False`? Is the only advantage now that other integer-like types are checked with `numbers.Integral`? – xuiqzy Feb 09 '21 at 20:41
  • 4
    Is the last section incorrect? `isinstance(12, float)` returns `False` for me. – jcai Sep 24 '21 at 18:35
155

I like @ninjagecko's answer the most.

This would also work:

for Python 2.x

isinstance(n, (int, long, float)) 

Python 3.x doesn't have long

isinstance(n, (int, float))

there is also type complex for complex numbers

Mostafa Fateen
  • 849
  • 1
  • 14
  • 33
Dan H
  • 14,044
  • 6
  • 39
  • 32
  • 3
    A sidenote, because booleans will resolve to True (e.g. `isinstance(False, (int, float)) = True`), I needed `not isinstance(n, bool) and isinstance(n, (int, float))` instead – YTZ Jun 07 '20 at 16:53
  • 4
    Lifesaver.. I did not notice `isinstance()` could check for multiple types.. – Ozkan Serttas Sep 11 '21 at 07:18
64

(note: this will return True for type bool, at least in cpython, which may not be what you want. Thank you commenters.)

One-liner:

isinstance(yourNumber, numbers.Real)

This avoids some problems:

>>> isinstance(99**10,int)
False

Demo:

>>> import numbers

>>> someInt = 10
>>> someLongInt = 100000L
>>> someFloat = 0.5

>>> isinstance(someInt, numbers.Real)
True
>>> isinstance(someLongInt, numbers.Real)
True
>>> isinstance(someFloat, numbers.Real)
True
ninjagecko
  • 88,546
  • 24
  • 137
  • 145
15

You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"
William Gerecke
  • 371
  • 2
  • 7
  • @dylnmc Then you can use the isinstance() method to determine if x is a number. Also, 3.2 % 1 yields 0.2. If a number is evenly divisible by 1, it is an integer numerically. This method was useful to me even though it may not have been for you. – William Gerecke Oct 02 '17 at 02:36
  • this is true; `x%1 == 0` should be true for only ints (but it will also be true for floats with only a zero following decimal point). If you know it's going to be an int (eg, if this is a param to a function), then you could just check with modulo. I bet that is faster than `Math.floor(x) == x`. On the not-so-bright side, this will be `True` if you pass a float like `1.0` or `5.0`, and you will encounter the same problem using what the original poster mentioned in his/her question. – dylnmc Oct 10 '17 at 14:11
11

It's easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn't work, the object was not of a suitable type. Knowing the type rarely helps.

Simply attempt the operation and see if it works.

inNumber = somenumber
try:
    inNumberint = int(inNumber)
    print "this number is an int"
except ValueError:
    pass
try:
    inNumberfloat = float(inNumber)
    print "this number is a float"
except ValueError:
    pass
shea
  • 1,129
  • 2
  • 21
  • 38
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 5
    Is there any reason to do this when `type` and `isinstance` can do the job? – user225312 Dec 27 '10 at 19:28
  • 11
    int(1.5) doesn't raise ValueError, and you obviously know that--giving a wrong answer on purpose? Seriously? – Glenn Maynard Dec 27 '10 at 19:57
  • 5
    @Glenn: I assume S.Lott understood the question as "check if a **string** is an int or float" (in which case it would actually be a good solution). –  Dec 27 '10 at 20:00
  • @A A: `class MetaInt(type): pass; class Int(int): __metaclass__ = MetaInt; type(Int(1)) == int`. (Sorry for the bad syntax but I cannot do more on one line.) – mg. Dec 27 '10 at 20:13
  • 2
    @A A: Yes. The reason is that this is simpler and more reliable. The distinction between `int` and `float` may not even be relevant for many algorithms. Requesting the type explicitly is usually a sign of bad polymorphism or an even more serious design problem. In short. Don't Check for Types. It's Easier to Ask Forgiveness than Ask Permission. – S.Lott Dec 27 '10 at 21:06
  • `import math; print math.isnan('hi')` fails for me because `isnan` expects an `int` or a `float`. I want to wrap it so that `_isnan('hi')` does return `False` for me. I want `_isnan(float('nan'))` to return `True` but `_isnan('nan')` to return `False`. The reason why is somewhat complicated - it has to do with sending JSON-like input to a custom web service we want a distinction between `?x="nan"` and `?x=nan` (when supplied in the URL). Now, I believe that your approach would treat `'nan'` and `float('nan')` the same way. That is not what I want. Is the problem with duck types or math.isnan? – Hamish Grubijan Dec 06 '12 at 15:15
  • This is the Pythonic way. – Daniel Standage Jun 30 '16 at 04:13
  • I would inverse the 2 blocs to start with `float` then `int`. Otherwise `'3'` will be seen as a float whereas it is actually an int. – Frodon Jul 11 '17 at 16:31
10

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"
user274595
  • 418
  • 1
  • 5
  • 15
  • 8
    This would fail in the [admittedly rare] case that the number in question is a SUBCLASS of int or float. (Hence why "isinstance" would be considered "better", IMO.) – Dan H Dec 14 '18 at 19:10
9

Tried in Python version 3.6.3 Shell

>>> x = 12
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x,int)
True

Couldn't figure out anything to work for.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ella
  • 101
  • 1
  • 5
8

Here's a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.

import sys

if sys.version < '3':
    integer_types = (int, long,)
else:
    integer_types = (int,)

isinstance(yourNumber, integer_types)  # returns True if it's an integer
isinstance(yourNumber, float)  # returns True if it's a float

Notice that Python 2 has both types int and long, while Python 3 has only type int. Source.

If you want to check whether your number is a float that represents an int, do this

(isinstance(yourNumber, float) and (yourNumber).is_integer())  # True for 3.0

If you don't need to distinguish between int and float, and are ok with either, then ninjagecko's answer is the way to go

import numbers

isinstance(yourNumber, numbers.Real)
Agostino
  • 2,723
  • 9
  • 48
  • 65
7

how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever
krakowi
  • 583
  • 5
  • 17
7

I know it's an old thread but this is something that I'm using and I thought it might help.

It works in python 2.7 and python 3< .

def is_float(num):
    """
    Checks whether a number is float or integer

    Args:
        num(float or int): The number to check

    Returns:
        True if the number is float
    """
    return not (float(num)).is_integer()


class TestIsFloat(unittest.TestCase):
    def test_float(self):
        self.assertTrue(is_float(2.2))

    def test_int(self):
        self.assertFalse(is_float(2))
Shahar
  • 2,101
  • 18
  • 23
6

I am not sure why this hasn't been proposed before, but how about using the built-in Python method on a float called is_integer()? Basically you could give it some number cast as a float, and ask whether it is an integer or not. For instance:

>>> (-13.0).is_integer()
True

>>> (3.14).is_integer()
False

For completeness, however, consider:

isinstance(i, int) or i.is_integer()
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Kris Stern
  • 1,192
  • 1
  • 15
  • 23
  • 1
    It's a very good proposition. It's a build-in fonction so it's good ! It can be apply to a series with a lambda. ```python _df["col_to_test].apply(lambda x : x.is_integer()) ``` – Nicoolasens Nov 12 '21 at 13:44
5

pls check this: import numbers

import math

a = 1.1 - 0.1
print a 

print isinstance(a, numbers.Integral)
print math.floor( a )
if (math.floor( a ) == a):
    print "It is an integer number"
else:
    print False

Although X is float but the value is integer, so if you want to check the value is integer you cannot use isinstance and you need to compare values not types.

M.Hefny
  • 2,677
  • 1
  • 26
  • 30
5

You can do it with simple if statement

To check for float

if type(a)==type(1.1)

To check for integer type

if type(a)==type(1)

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Alwyn Miranda
  • 370
  • 3
  • 5
  • 18
2
absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ajay Prajapati
  • 668
  • 1
  • 10
  • 18
1

Update: Try this


inNumber = [32, 12.5, 'e', 82, 52, 92, '1224.5', '12,53',
            10000.000, '10,000459', 
           'This is a sentance, with comma number 1 and dot.', '121.124']

try:

    def find_float(num):
        num = num.split('.')
        if num[-1] is not None and num[-1].isdigit():
            return True
        else:
            return False

    for i in inNumber:
        i = str(i).replace(',', '.')
        if '.' in i and find_float(i):
            print('This is float', i)
        elif i.isnumeric():
            print('This is an integer', i)
        else:
            print('This is not a number ?', i)

except Exception as err:
    print(err)
Magotte
  • 143
  • 10
0

Use the most basic of type inference that python has:

>>> # Float Check
>>> myNumber = 2.56
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
True
>>> print(type(myNumber) == bool)
False
>>>
>>> # Integer Check
>>> myNumber = 2
>>> print(type(myNumber) == int)
True
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
False
>>>
>>> # Boolean Check
>>> myNumber = False
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
True
>>>

Easiest and Most Resilient Approach in my Opinion

-1
def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer
  • func checks for ints but also returns true for floats that are .0 – Gideon Bamuleseyo Nov 03 '17 at 18:13
  • Please explain why/how your contribution solves the OPs question. – Heri Nov 03 '17 at 19:17
  • @Heri he is looking to check if a number is an int or a float, the function I defined can do that, abs is an inbuilt python func that returns the absolute value of the number, round is also an inbuilt func that rounds off the number, if I subtract the rounded number from the absolute one, and I get a zero, then the number is an int, or it has a zero as after its decimal places – Gideon Bamuleseyo Nov 04 '17 at 18:28
-1

Try this...

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0
Ramkumar G
  • 17
  • 1
  • 7
-5

variable.isnumeric checks if a value is an integer:

 if myVariable.isnumeric:
    print('this varibale is numeric')
 else:
    print('not numeric')
Raviteja
  • 3,399
  • 23
  • 42
  • 69
person
  • 1