DEV Community

Cover image for Python Check If Number is an Integer
Victor Chendra
Victor Chendra

Posted on

Python Check If Number is an Integer

Simply here is the ultimate code...

def is_int(x: int | float | str | None):
    try:
        return float(x).is_integer()
    except (TypeError, ValueError):
        return False
Enter fullscreen mode Exit fullscreen mode

TypeError if we try to float(None).
ValueError if x is a string and contain non-digit characters.

Example usage (test cases)

a1 = 12.0  # True
a2 = "12.0"  # True
a3 = "012.0"  # True

b1 = 12  # True
b2 = "12"  # True
b3 = "012"  # True

c1 = 12.34  # False
c2 = "12.34"  # False
c3 = "012.34"  # False

d1 = None  # False
d2 = "12X100ML"  # False
d3 = "12.x"  # False

print(is_int(a1))
print(is_int(a2))
print(is_int(a3))

print(is_int(b1))
print(is_int(b2))
print(is_int(b3))

print(is_int(c1))
print(is_int(c2))
print(is_int(c3))

print(is_int(d1))
print(is_int(d2))
print(is_int(d3))
Enter fullscreen mode Exit fullscreen mode

Explanation (how it started)

A simple isinstance(x, int) won't work fully enough. It fails when cases like this:

  1. Number stored as str.
  2. Integer but represented as float type (ex. x=12.0 technically it's an integer value right.).
  3. Or some edge cases where string like "abc" or "12.x" should gracefully return False rather than crashing.

This is important when we work for web forms, APIs, type strict column on database like on Django (for ex. models.PositiveIntegerField, etc.).

Here is how my initial code was before getting simplified in the code above.

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
Enter fullscreen mode Exit fullscreen mode

Yes, you can use regex, but I think it's more complex and why not use the built-in.

For regex version, check on my other post.

Top comments (0)