Python Check If Number is an Integer
Source: Dev.to
def is_int(x: int | float | str | None):
"""
Return True if *x* represents an integer value, otherwise False.
Handles:
- int, float, and numeric strings (e.g., "12", "12.0")
- None or non‑numeric strings gracefully return False
"""
try:
return float(x).is_integer()
except (TypeError, ValueError):
return False
How it works
float(x)attempts to convert the input to a floating‑point number.is_integer()checks whether the resulting float has no fractional part.- If the conversion fails (e.g.,
xisNoneor a non‑numeric string), aTypeErrororValueErroris caught and the function returnsFalse.
Example usage (test cases)
# Positive cases – should return True
a1 = 12.0
a2 = "12.0"
a3 = "012.0"
b1 = 12
b2 = "12"
b3 = "012"
# Negative cases – should return False
c1 = 12.34
c2 = "12.34"
c3 = "012.34"
d1 = None
d2 = "12X100ML"
d3 = "12.x"
print(is_int(a1)) # True
print(is_int(a2)) # True
print(is_int(a3)) # True
print(is_int(b1)) # True
print(is_int(b2)) # True
print(is_int(b3)) # True
print(is_int(c1)) # False
print(is_int(c2)) # False
print(is_int(c3)) # False
print(is_int(d1)) # False
print(is_int(d2)) # False
print(is_int(d3)) # False
Why isinstance(x, int) isn’t enough
- String numbers:
"12"or"12.0"are notintinstances. - Floats that are mathematically integers:
12.0is afloatbut represents an integer value. - Invalid inputs: Non‑numeric strings like
"abc"or"12.x"should returnFalsewithout raising an exception.
Alternative (more verbose) implementation
def is_int(x: int | float | str | None):
if isinstance(x, str):
try:
x = float(x)
except (TypeError, ValueError):
return False
if isinstance(x, int):
return True
if isinstance(x, float):
return x.is_integer()
return False
Regex approach
A regular‑expression solution is possible but adds unnecessary complexity. The built‑in conversion shown above is concise and reliable. (For a regex version, see my other post.)