Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check if a float value is a whole number in Python?
To check if a float value is a whole number in Python, you can use several methods. The most straightforward approach is using the is_integer() method available for float objects.
Using the is_integer() Method
The is_integer() method returns True if the float value represents a whole number, otherwise False ?
print((10.0).is_integer()) print((15.23).is_integer()) print((-5.0).is_integer()) print((0.0).is_integer())
True False True True
Using Modulo Operation
You can also check if a float is a whole number by using the modulo operator to see if there's no remainder when divided by 1 ?
def is_whole_number(num):
return num % 1 == 0
print(is_whole_number(7.0))
print(is_whole_number(7.5))
print(is_whole_number(-3.0))
True False True
Using int() Conversion
Another approach is to compare the float with its integer conversion ?
def is_whole_number(num):
return num == int(num)
print(is_whole_number(12.0))
print(is_whole_number(12.7))
print(is_whole_number(-8.0))
True False True
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
is_integer() |
num.is_integer() |
Most readable and direct |
| Modulo Operation | num % 1 == 0 |
Mathematical approach |
| Int Conversion | num == int(num) |
Works with edge cases |
Conclusion
The is_integer() method is the most Pythonic way to check if a float is a whole number. Use modulo or int conversion for custom functions or when working with different numeric types.
Advertisements
