295

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?

6
  • 12
    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. Commented Dec 27, 2010 at 19:21
  • 4
    related: How to check if a float value is a whole number. Commented Oct 19, 2014 at 11:47
  • @Wooble: it fails for larger numbers. Commented Oct 19, 2014 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. Commented Mar 28, 2015 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. Commented Oct 26, 2017 at 17:39

19 Answers 19

415

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 
Sign up to request clarification or add additional context in comments.

13 Comments

@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)
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).
For Python 2, there is also the direct double check: isinstance(x, (int, long)).
WARNING: bools are instances of integers also. See isinstance(True, int)
Is the last section incorrect? isinstance(12, float) returns False for me.
|
166

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

2 Comments

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
Lifesaver.. I did not notice isinstance() could check for multiple types..
68

(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 

3 Comments

In Python 3 isinstance(99**10,int) is True.
This also passes Bool. instance(True, numbers.Real) is True
@carkod. Because bool is a subclass of int
16

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" 

2 Comments

@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.
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.
12

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 

9 Comments

Is there any reason to do this when type and isinstance can do the job?
int(1.5) doesn't raise ValueError, and you obviously know that--giving a wrong answer on purpose? Seriously?
@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).
@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.)
@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.
|
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" 

1 Comment

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

Comments

9

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

1 Comment

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

Comments

7

how about this solution?

if type(x) in (float, int): # do whatever else: # do whatever 

Comments

6

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

Comments

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)

1 Comment

Why evaluate the right side when you can use int or float? Don't use this for this case.
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.

Comments

2
absolute = abs(x) rounded = round(absolute) if absolute - rounded == 0: print 'Integer number' else: print 'notInteger number' 

Comments

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) 

3 Comments

Yes I did and it didn't work. And I'm pretty sure you didn't really try it. Because it doesn't work.
Certainly, there is a less offensive way to respond. Although you are right I just run more test's it doesn't work in every case.
@JJJ How about this solution?
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

Comments

-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 

3 Comments

func checks for ints but also returns true for floats that are .0
Please explain why/how your contribution solves the OPs question.
@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
-1

Try this...

def is_int(x): absolute = abs(x) rounded = round(absolute) return absolute - rounded == 0 

Comments

-5

variable.isnumeric checks if a value is an integer:

 if myVariable.isnumeric: print('this varibale is numeric') else: print('not numeric') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.