I have just started in Python.
Is there a way to check whether a particular number is integer or not.
e.g. x=12.33
I have just started in Python.
Is there a way to check whether a particular number is integer or not.
e.g. x=12.33
There are multiple ways in python to solve this.
If you want to confirm the datatype then do then the recommended way is -
x = 12.33
isinstance(x, int)
#False
isinstance(x, float)
#True
The above approach is agnostic to the type of object x is to begin with.
You can also try the following ways -
x = 12.33
type(x) == int
#False
type(x) == float
#True
## This approach is not recommended as the is_integer method is available only for float type objects
x.is_integer()
#False
If the variable is originally a string, but you still wanna check if the element is potentially a numeric type then -
x = '12.33'
x.isnumeric()
#False
x.isdigit()
#False
x.isdecimal()
#True
if type(x) == int
. type(variable)
returns type of object. You just compare it with what you want
If the variable is already a number (float), you can use float.is_integer()
>>> i = 4.0
>>> i.is_integer()
True
>>> i = 4.1
>>> i.is_integer()
False
You can use type(var)
to check the data type.
x = 12.33
if type(x) == int:
print("Integer")
elif type(x) == float:
print("Float")
Use type(<variable>)
function to determine the data type of it (Use if case for this). It will help!
As some answers have suggested you can check the type of the variable, for instance:
x = 2
type(x) == int
however, if you want to check if the number is an integer even if it's stored as a float you could cast it to a float and compare it with itself. i.e.
x = 2.000
int(x) == x
# True
y = 1.2043
int(y) == y
# False
If it is not an integer value the typecasting will truncate the number to just the integer part and it will no longer be equal. It's worth noting this may not work for very large integers due to floating-point errors.