Check if a number is int or float
PythonPython Problem Overview
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?
Python Solutions
Solution 1 - Python
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
Solution 2 - Python
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
Solution 3 - Python
(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
Solution 4 - Python
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"
Solution 5 - Python
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
Solution 6 - Python
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"
Solution 7 - Python
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)
Solution 8 - Python
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.
Solution 9 - Python
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))
Solution 10 - Python
how about this solution?
if type(x) in (float, int):
# do whatever
else:
# do whatever
Solution 11 - Python
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.
Solution 12 - Python
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 weather it is an integer or not. For instance:
>>> (-13.0).is_integer()
True
>>> (3.14).is_integer()
False
For more information about this method, please see https://docs.python.org/3/library/stdtypes.html#float.is_integer.
Solution 13 - Python
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)
Solution 14 - Python
absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
print 'Integer number'
else:
print 'notInteger number'
Solution 15 - Python
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)
Solution 16 - Python
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
Solution 17 - Python
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
Solution 18 - Python
Try this...
def is_int(x):
absolute = abs(x)
rounded = round(absolute)
return absolute - rounded == 0
Solution 19 - Python
variable.isnumeric
checks if a value is an integer:
if myVariable.isnumeric:
print('this varibale is numeric')
else:
print('not numeric')