How to Check If a Float Number Is an Integer in Python
In Python, floating-point numbers (float) are approximations of real numbers. Due to how computers store decimals (IEEE 754 standard), a float might look like an integer (e.g., 5.0) or have a tiny decimal remainder due to precision errors (e.g., 3.0000000000000004).
This guide explains how to check if a float represents a whole number using the built-in is_integer() method, direct integer comparison, and modulo arithmetic.
Understanding Floating-Point Precision
Before checking if a number is an integer, it's vital to understand that floats are often imprecise.
val = 0.1 + 0.2
print(f"Value: {val}")
Output:
Value: 0.30000000000000004
Although mathematically 0.1 + 0.2 = 0.3, the computer stores it with a tiny error. A strict integer check might fail here unless you round the number first.
Method 1: Using float.is_integer() (Recommended)
Python float objects have a built-in method .is_integer() that returns True if the float has no fractional part.
num1 = 5.0
num2 = 5.5
# ✅ Correct: Using the built-in method
print(f"{num1} is integer? {num1.is_integer()}")
print(f"{num2} is integer? {num2.is_integer()}")
Output:
5.0 is integer? True
5.5 is integer? False
Method 2: Using the Modulo Operator %
You can use the modulo operator % 1. If a number divided by 1 has a remainder of 0, it is an integer.
def check_integer_modulo(n):
return n % 1 == 0
print(f"4.0: {check_integer_modulo(4.0)}")
print(f"4.2: {check_integer_modulo(4.2)}")
Output:
4.0: True
4.2: False
Method 3: Comparing with Casted Integer
Another common approach is checking if the float is equal to itself cast as an integer.
num = 12.0
# Logic: 12.0 == int(12.0) -> 12.0 == 12 -> True
# Logic: 12.5 == int(12.5) -> 12.5 == 12 -> False
if num == int(num):
print(f"{num} is effectively an integer.")
else:
print(f"{num} has a decimal part.")
Output:
12.0 is effectively an integer.
Handling Precision Errors (Tolerance)
If you are dealing with calculation results (like 0.1 + 0.2), standard checks return False. You might need to use a tolerance (epsilon).
import math
val = 0.1 + 0.2 # 0.30000000000000004
# ⛔️ Standard check fails
print(f"Is integer? {val.is_integer()}")
# ✅ Correct: Check if it's "close enough" to an integer
# We check if the distance to the nearest integer is tiny
is_close = math.isclose(val, round(val), rel_tol=1e-9) # 0.3 is NOT an integer, but this logic helps for numbers like 3.000000004
# Better example: 3.0000000000000004
val2 = 3.0 + 4e-16
print(f"Value 2: {val2}")
print(f"Close to int? {math.isclose(val2, round(val2))}")
Output:
Is integer? False
Value 2: 3.0000000000000004
Close to int? True
Conclusion
To check if a float has no decimal part:
- Use
x.is_integer()for the cleanest, most Pythonic solution. - Use
x % 1 == 0as a mathematical alternative suitable for other languages too. - Use
math.isclose()if your float comes from imprecise calculations and might have a microscopic remainder.