Check if a float is a whole number in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Check if a float is a whole number in Python #

Use the float.is_integer() method to check if a float is a whole number, e.g. result = (3.00).is_integer(). The float.is_integer method will return True if the float is a finite, whole number, otherwise it returns False.

main.py
import math # ✅ check if float is whole number using float.is_integer() result_1 = (3.00).is_integer() print(result_1) # 👉️ True # ----------------------------------- # ✅ check if float is whole number using modulo num = 5.00 result_2 = num % 1 == 0 print(result_2) # 👉️ True # ------------------------------------ # ✅ check if float is whole number using math.floor() num = 7.00 result_3 = math.floor(num) == num print(result_3) # 👉️ True

The first example uses the float.is_integer() method to check if a float is a whole number.

The float.is_integer method returns a boolean result:

  • True if the floating-point number is a finite, whole number
  • False if it isn't
main.py
print((3.00).is_integer()) # 👉️ True print((3.14).is_integer()) # 👉️ False

Alternatively, you can use the modulo operator.

Check if a float is a whole number using modulo #

To check if a float is a whole number:

  1. Use the modulo operator to divide the float by 1.
  2. If the remainder from the division is 0, the number is whole.
  3. If the remainder isn't 0, the number has a decimal point.
main.py
num = 5.00 result = num % 1 == 0 print(result) # 👉️ True

The modulo (%) operator returns the remainder from the division of the first value by the second.

main.py
print(10 % 1) # 👉️ 0 print(10.5 % 1) # 👉️ 0.5

If the remainder we get from dividing the number by 1 is 0, then we have a whole number.

Conversely, if there is a remainder from dividing by 1, the number has a decimal point.

Alternatively, you can use the math.floor() method.

Check if a float is a whole number using math.floor() #

To check if a float is a whole number:

  1. Pass the number to the math.floor() method.
  2. The math.floor() method will round the number down.
  3. Compare the rounded down number with the number itself.
main.py
import math num = 7.00 result = math.floor(num) == num print(result) # 👉️ True

The math.floor method returns the largest integer less than or equal to the provided number.

main.py
print(math.floor(3.99)) # 👉️ 3 print(math.floor(3.00)) # 👉️ 3

If the rounded down number is equal to the number itself, then we have a whole number.

If the rounded down number is different, the number has a decimal point.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.