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?
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 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).isinstance(x, (int, long)).isinstance(True, int)isinstance(12, float) returns False for me.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
isinstance(False, (int, float)) = True), I needed not isinstance(n, bool) and isinstance(n, (int, float)) insteadisinstance() could check for multiple types..(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 isinstance(99**10,int) is True.Bool. instance(True, numbers.Real) is TrueYou 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" 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.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 type and isinstance can do the job?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.)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.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" 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() python _df["col_to_test].apply(lambda x : x.is_integer()) 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) 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)) You can do it with simple if statement
if type(a)==type(1.1)
if type(a)==type(1)
int or float? Don't use this for this case.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.
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) 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
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
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.somenumber?" 2) Issomenumbera whole number? 3) Issomenumbera 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.