How to check if a number is float or not in Python
In this tutorial, we will learn how to check if a number is float or not in Python. We can check this in three different ways.
- type() method
- comparing with “float”
- isinstance()
A more precise number with decimal is float number. We also refer to it as a floating-point number. In python, it is very easy to check whether the number is float or not. Here are the few methods. Let’s start with type() in Python.
Check type of variable
num = 34.22 print(type(num))
Output:
<class ‘float’>
Comparison with ‘float’
num = 34.22 if(num == float): print('This number is float') else: print('This number is not float')
Output:
This number is float
Use isinstance() method to check if a number is float or not in Python
num = 34.22 print(isinstance(num, float)
Output:
True
In the above example, isinstance() is used to check whether the first argument is an object or ‘instance’ of the second argument or not.
You may also read:
- Check whether a variable is defined or not in Python
- Scope of a variable, global and non-local keyword in Python
This does not work cmon
num = 34.22
if(num == float):
print(‘This number is float’)
else:
print(‘This number is not float’)
What if we take input from user.. its returns always a string..
Try adding in the type method.
if(type(num) == float):
print(“a float”)
else:
print(“not a float”)
The type() method either returns the type of the specified object or returns a new type object of the specified dynamic class, based on the specified class name, base classes and class body.