How to Check if a Number is an Integer or a Float in Python

In Python, you have a variety of methods at your disposal to determine whether a value is an integer or a float. The best method to use often depends on your specific use case. Let’s briefly outline the common approaches:

  • Using type(): This function is the most straightforward way to directly get the data type of any variable in Python.
  • Using isinstance(): This function checks an object’s type and is generally preferred over type() as it supports inheritance.
  • Using float.is_integer(): Apply this method to a float to determine if it can be represented as an integer without losing precision.
  • Using the Modulo Operator (%): Use this operator to check if a number has no remainder when divided by 1, which helps in identifying if a float is effectively an integer.
  • Using Regular Expressions: Ideal for parsing and validating string representations of numbers to see if they conform to integer or float patterns.
  • Using math.modf(): This function separates the number into its integer and fractional parts, allowing you to check for the presence of a decimal component.

Let’s explore each method in more detail.

Using the type() Function

The type() function is a straightforward way to directly get the data type of any variable in Python. You pass the variable you want to check to the type() function, and it returns its type.

To determine if a number is an integer or float, you compare the result with int or float.

print(type(5) is int)        # Output: True
print(type(3.14) is int)     # Output: False

print(type(5) is float)      # Output: False
print(type(3.14) is float)   # Output: True

Using the isinstance() Function

The isinstance() function is more flexible when you need to check if a variable belongs to a particular type. It takes two arguments: the variable you want to check and the data type you’re checking against. It returns True if the variable is an instance of the specified type and False otherwise.

print(isinstance(5, int))        # Output: True
print(isinstance(3.14, int))     # Output: False

print(isinstance(5, float))      # Output: False
print(isinstance(3.14, float))   # Output: True

For type checking, the isinstance() function is generally preferred because it supports inheritance. This means that if you have classes and subclasses, isinstance() will correctly recognize a subclass object as an instance of its parent class. While inheritance isn’t relevant here with simple types like integers and floats, using isinstance() is still considered good practice.

Comparing with integer representation

This method relies on the fact that if a number is already an integer, attempting to convert it to an integer using the int() function won’t change its value. Conversely, if the number is a float, converting it to an integer will truncate the decimal part. By comparing the original number to its integer-converted version, you can determine its type. If they are equal, the original number was an integer; otherwise, it was a float.

num1 = 5
num2 = 3.14

print(num1 == int(num1))   # Output: True
print(num2 == int(num2))   # Output: False

Using the float.is_integer() Method

The .is_integer() method is specifically designed for float values. It tells you if a float value can be represented as an integer without losing precision.

If a float has no fractional part after the decimal point (like 20.0), it’s considered an integer from a representational perspective, and .is_integer() would return True. However, if the float has a decimal component (like 18.5), then .is_integer() would return False.

print((1.0).is_integer())     # Output: True (as 1.0 can be represented as an integer)
print((3.14).is_integer())    # Output: False (because it has a fractional part)
print((-1.0).is_integer())    # Output: True (negative but still an integer)

Using the Modulo Operator (%)

The modulo operator % provides the remainder when you divide one number by another. A key property of integers is that they are always evenly divisible by 1, leaving no remainder. If you use the modulo operator on a number with 1 (num % 1) and the result is 0, you can conclude that the number is an integer. This method leverages this mathematical concept to determine the data type.

print(5 % 1 == 0)       # Output: True
print(3.14 % 1 == 0)    # Output: False
print(10.0 % 1 == 0)    # Output: True
print(-1.0 % 1 == 0)    # Output: True

Using Regular Expressions

For input validation, especially when reading from files or user input where numbers might be represented as strings, you can use regular expressions to determine if a string represents an integer or a float.

import re

def detect_number_type(number):
    if re.match(r"^\d+$", number):
        return "Integer"
    elif re.match(r"^\d+\.\d+$", number):
        return "Float"
    else:
        return "Unknown"

print(detect_number_type("5"))     # Output: Integer
print(detect_number_type("3.14"))  # Output: Float
print(detect_number_type("10.0"))  # Output: Float

In this code, the detect_number_type() function uses regular expressions to classify numeric strings. The first pattern ^\d+$ checks for integers (whole numbers), and the second pattern ^\d+\.\d+$ checks for floats (numbers with decimal parts). If the string doesn’t match either pattern, it’s classified as “Unknown”.

Using the Math Module

If you’re performing numerical calculations and need to specifically determine whether a number has a fractional part, you can use the math.modf() function. This function returns a tuple containing the fractional and integer parts of the input number. By checking if the fractional part is zero, you can reliably determine if the original number was an integer or a float.

import math

def detect_number_type(number):
    fractional, integer = math.modf(number)
    if fractional == 0:
        return "Integer"
    else:
        return "Float"

print(detect_number_type(5))     # Output: Integer
print(detect_number_type(3.14))  # Output: Float
print(detect_number_type(10.0))  # Output: Integer
print(detect_number_type(-1.0))  # Output: Integer