Explain Codes LogoExplain Codes Logo

Check if a number is int or float

python
functions
best-practices
collections
Alex KataevbyAlex Kataev·Feb 1, 2025
TLDR

Fast and furious check if x is int or float using isinstance() function in Python:

x = 42.0 # the answer to life, universe and everything is_int = isinstance(x, int) # False, it's not an integer but a philosophical float is_float = isinstance(x, float) # True, because any truth in the universe is a float

Double-check: Including all numerical types

Beyond integers and floating point numbers, Python processes other numerical types such as complex and fractional numbers.

import numbers # Don't be afraid of long numbers, Python can handle your fear n = 12345678901234567890 is_long_int = isinstance(n, numbers.Integral) # True for long integers in Python 2.x

Remember numbers.Integral checks for both plain and long integers.

# Python plays well with all real numbers because it’s a realist n = 987.65 is_real = isinstance(n, numbers.Real) # True for both ints and floats

Here, numbers.Real checks if a value is any real number – int or float.

Extra mile: Explore different approaches

Crafty modulo trick

You can play the spy who loved integers, revealing their disguises:

n = 18.0 is_integer_in_disguise = n % 1 == 0 # True for float numbers running under deep cover as integers.

By applying modulo (remainder) operation, we find out if the number has left any fractional part.

The try-except hero

In a world where every line of code is a battle, try-except comes to the rescue:

num = '10.0' try: hero = int(num) except ValueError: print(f"{num} is a cryptic float or a villain impersonating an int!")

Here, int casting attempts to convert the number. A ValueError is your friend revealing the sneakiest floats and the baddest non-integers in town.

Stepping into the shoes of a number

Imagine numbers like containers filled with exact or spill-over amounts of liquid:

| Container (Number) | Exact liters (Int)? | Spillage (Float)? | | ------------------ | ------------------- | ----------------- | | Bucket '7' | Yes. Holds **7** | No spillage 🪣✅ | | Cup '7.5' | No | Spills 0.5 🥤💧 |

In Python, type checks can help determine the nature of these containers:

num = 7 isinstance(num, int) # A bucket with no spills. It's a perfect `int`. 🪣✅ num = 7.5 isinstance(num, float) # A cup that spills. Definitely `float`. 🥤💧

Buckets are int. Spillers are float.

Customizing the check

A function can encapsulate this check, for a cleaner and more reusable code pattern, because every hero deserves a clean home:

def is_integer(n): return isinstance(n, numbers.Integral) # Number’s driver's license check. Passes for only integers. print(is_integer(2)) # True print(is_integer(2.5)) # False

Mind the version

Remember, Python 2.x and Python 3.x are like Coke Classic and Diet Coke to integers. Treat int and long differently in 2.x:

  • Python 2.x: isinstance(n, (int, long, float))
  • Python 3.x: isinstance(n, (int, float)) # Python’s answer to Diet Coke – int and float are everything you need!

Types shape the operation

Remember, knowing the type is not for bragging rights, but to influence the operation's outcome. It can affect rounding and precision. So, pay attention, or your math could spill over.