The easiest way to check if a number is a whole number in Python is using the is_integer() function.
print((2.0).is_integer())
print((2.01).is_integer())
#Output:
True
False
You can also check if the number minus the integer conversion of the number is equal to 0.
print(2.0 - int(2.0) == 0)
print(2.01 - int(2.01) == 0)
#Output:
True
False
In Python, when working with numbers, it can be useful to be able to find out if a number is a whole number.
We can easily check if a number is a whole number with the help of the float is_integer() function.
The is_integer() function returns a boolean indicating if the float is an integer or not.
Below are some examples of how to use the Python is_integer() function to check if a number is a whole number.
print((2.0).is_integer())
print((2.01).is_integer())
#Output:
True
False
Checking if a Number is a Whole Number Using Integer Conversion in Python
You can also check if a number is a whole number using integer conversion in Python. If we convert a floating point number to an integer, then the difference between the number and the newly created integer should be 0 if the number is a whole number.
Below are some examples of how you can use integer conversion to check if number is whole.
print(2.0 - int(2.0) == 0)
print(2.01 - int(2.01) == 0)
#Output:
True
False