Check if a number is an Integer or Float in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
8 min

banner

# Table of Contents

  1. Check if a number is an int or float in Python
  2. Check if a string is an Integer or a Float in Python
  3. Check if a string can be converted to an Integer in Python
  4. Check if a string can be converted to a float in Python
  5. Check if a float is a whole number in Python

# Check if a number is an int or float in Python

Use the isinstance() function to check if a number is an int or float.

The isinstance function will return True if the passed-in object is an instance of the provided class (int or float).

main.py
my_num = 1357 if isinstance(my_num, int): print('number is int') if isinstance(my_num, float): print('number is float') # ----------------------------------- # โœ… checks if a number is either int or float if isinstance(my_num, (int, float)): print('Number is either int or float')

check if number is int or float

The code for this article is available on GitHub

We used the isinstance() function to check if a number is an int or a float.

The isinstance function returns True if the passed-in object is an instance or a subclass of the passed-in class.

main.py
print(isinstance(357, int)) # ๐Ÿ‘‰๏ธ True print(isinstance(357, float)) # ๐Ÿ‘‰๏ธ False print(isinstance(3.14, float)) # ๐Ÿ‘‰๏ธ True print(isinstance(3.14, int)) # ๐Ÿ‘‰๏ธ False

The isinstance() function correctly returns whether the passed-in object is an instance or a subclass of the provided class.

However, there is an edge case - booleans are also an instance of integers.

main.py
print(isinstance(True, int)) # ๐Ÿ‘‰๏ธ True print(isinstance(False, int)) # ๐Ÿ‘‰๏ธ True

This is because the bool class is a subclass of int.

If you need to check if a number is either int or float, pass a tuple containing the int and float classes in the call to the isinstance() function.

main.py
my_num = 1357 if isinstance(my_num, (int, float)): # ๐Ÿ‘‡๏ธ this runs print('Number is either int or float')

checking if number is either int or float

The code for this article is available on GitHub
The second argument the isinstance function takes can be a class or a tuple containing multiple classes.

The call to the function above checks if the passed-in object is either an int or a float.

Using a tuple in the call to the function is equivalent to using two calls with the OR operator.

main.py
my_num = 1357 if isinstance(my_num, int) or isinstance(my_num, float): print('Number is either int or float')

If you just want to print the type of the number, use the type() class.

main.py
my_num = 1357 print(type(my_num)) # ๐Ÿ‘‰๏ธ <class 'int'> my_num_2 = 3.14 print(type(my_num_2)) # ๐Ÿ‘‰๏ธ <class 'float'>

The type class returns the type of an object.

Most commonly the return value is the same as accessing the __class__ attribute on the object.

# Check if a string is an Integer or a Float in Python

To check if a string is an integer or a float:

  1. Use the str.isdigit() method to check if every character in the string is a digit.
  2. If the method returns True, the string is an integer.
  3. If the method returns False, the string is a floating-point number.
main.py
my_str = '2468' if my_str.isdigit(): my_num = int(my_str) print('String is an integer') else: my_num = float(my_str) print('String is a float') print(my_num) # ๐Ÿ‘‰๏ธ 2468

check if string is integer or float

The code for this article is available on GitHub
If you have to handle negative numbers, scroll down to the try/except solution.

We used the str.isdigit() method to check if all characters in the string are digits.

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

The str.isdigit() metho would return False if the string has a decimal point or starts with a minus - (is a negative number).

main.py
print('-123'.isdigit()) # ๐Ÿ‘‰๏ธ False print('1.23'.isdigit()) # ๐Ÿ‘‰๏ธ False

If you don't have to handle negative numbers, use the str.isdigit() method as it is sufficient.

If you have to handle negative numbers, use a try/except block.

# Check if a string is an Integer or a Float using try/except

This is a three-step process:

  1. Wrap the call to the int() class in a try block.
  2. If the call to the int() class succeeds, the string is an integer.
  3. If the except block runs, the string is a floating-point number.
main.py
my_str = '-2468' try: my_num = int(my_str) # ๐Ÿ‘‡๏ธ this runs print('String is an integer') except ValueError: my_num = float(my_str) print('String is a float') print(my_num) # ๐Ÿ‘‰๏ธ -2468

check if string is integer or float using try except

The code for this article is available on GitHub

We used a try/except statement to check if a string is an integer or a float.

If the try block runs successfully, the string is an integer.

If calling the int() class with the string raises a ValueError, the except block is run and the string is a floating-point number.

Unlike the str.isdigit() method, this approach also handles negative numbers.

Using a try/except statement in this manner is commonly known as "asking for forgiveness rather than permission".

We pass the string to the int() class not knowing whether the conversion will be successful, and if a ValueError error is raised, we handle it in the except block.

# Check if a String can be converted to an Integer in Python

To check if a string can be converted to an integer:

  1. Wrap the call to the int() class in a try/except block.
  2. If the conversion succeeds, the try block will fully run.
  3. If the conversion to integer fails, handle the ValueError in the except block.
main.py
def can_convert_to_int(string): try: int(string) return True except ValueError: return False print(can_convert_to_int('1357')) # ๐Ÿ‘‰๏ธ True print(can_convert_to_int('-1357')) # ๐Ÿ‘‰๏ธ True print(can_convert_to_int('1.357')) # ๐Ÿ‘‰๏ธ False print(can_convert_to_int('ABC123')) # ๐Ÿ‘‰๏ธ False

check if string can be converted to integer

The code for this article is available on GitHub

We used a try/except block to check if a string can be converted to an integer.

If the try block succeeds, the function returns True and the string can be converted to an integer.

If calling the int() class with the string fails, a ValueError is raised and the function returns False.

Using a try/except statement in this manner is commonly known as "asking for forgiveness rather than permission".

We pass the string to the int() class not knowing whether the conversion will be successful, and if a ValueError error is raised, we handle it in the except block.

# Check if String can be converted to Integer using isdigit()

Alternatively, you can use the str.isdigit() method.

If the str.isdigit method returns True, then all of the characters in the string are digits and it can be converted to an integer.

main.py
my_str = '1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) # ๐Ÿ‘‰๏ธ 1357 print('โœ… string can be converted to integer') else: print('โ›”๏ธ string CANNOT be converted to integer')
The code for this article is available on GitHub

We used the str.isdigit() method to check if a string can safely be converted to an integer.

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

The method checks if all characters in the string are digits, so if the string had a minus sign or a decimal, it would return False.

main.py
my_str = '-1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) print('โœ… string can be converted to integer') else: # ๐Ÿ‘‡๏ธ this runs print('โ›”๏ธ string CANNOT be converted to integer')
If your string might be a negative integer, use a try/except example instead, as it also covers negative integers.

If you just want to try converting the string to an integer and silence/ignore the ValueError if the conversion fails, use a pass statement.

main.py
my_str = '2468' try: my_int = int(my_str) print(my_int) # ๐Ÿ‘‰๏ธ 2468 except ValueError: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

main.py
class Employee: pass

# Check if a String can be converted to a Float in Python

To check if a string can be converted to a float:

  1. Wrap the call to the float() class in a try/except block.
  2. If the try block runs successfully, the string can be converted to a float.
  3. If the except block runs, the string cannot be converted to a float.
main.py
my_str = '3.456' try: result = float(my_str) print(result) # ๐Ÿ‘‰๏ธ 3.456 except ValueError: print('Value cannot be converted to a float')
The code for this article is available on GitHub

We used a try/except statement to check if a string can be converted to a float.

If the try block runs successfully, the string can be converted to a float.

If trying to convert the string to a float() raises a ValueError, the string cannot be converted to a float.
main.py
my_str = 'abc1.23' try: result = float(my_str) print(result) except ValueError: # ๐Ÿ‘‡๏ธ this runs print('Value cannot be converted to a float')

You can also extract the logic into a reusable function.

main.py
def can_convert_to_float(string): try: result = float(string) print(result) return True except ValueError: return False print(can_convert_to_float('123')) # ๐Ÿ‘‰๏ธ True print(can_convert_to_float('1.23')) # ๐Ÿ‘‰๏ธ True print(can_convert_to_float('a.bc')) # ๐Ÿ‘‰๏ธ False print(can_convert_to_float('.5')) # ๐Ÿ‘‰๏ธ True if can_convert_to_float('3.14'): # ๐Ÿ‘‡๏ธ this runs print('String can be converted to a float โœ…') else: print('String cannot be converted to a float โ›”๏ธ')
The code for this article is available on GitHub

If the try block succeeds, the function returns True.

If calling the float() class with the string fails, a ValueError is raised and the function returns False.

Using a try/except statement in this manner is commonly known as "asking for forgiveness rather than permission".

We pass the string to the float() class not knowing whether the conversion will be successful, and if a ValueError error is raised, we handle it in the except block.

If you want to silence/ignore the error when it's raised, use the pass statement.

main.py
my_str = 'ab.cd' try: result = float(my_str) print(result) except ValueError: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

# Check if a Float is a whole Number in Python

You can use the float.is_integer() method to check if a float is a whole number.

main.py
import math # โœ… Check if a float is a whole number using float.is_integer() result = (3.00).is_integer() print(result) # ๐Ÿ‘‰๏ธ True
The code for this article is available on GitHub

The first example uses the float.is_integer() method to check if a float is a whole number.

The float.is_integer method returns a boolean result:

  • True if the floating-point number is a finite, whole number
  • False if it isn't
main.py
print((3.00).is_integer()) # ๐Ÿ‘‰๏ธ True print((3.14).is_integer()) # ๐Ÿ‘‰๏ธ False

Alternatively, you can use the modulo operator.

# Check if a float is a whole number using modulo

This is a three-step process:

  1. Use the modulo operator to divide the float by 1.
  2. If the remainder from the division is 0, the number is whole.
  3. If the remainder isn't 0, the number has a decimal point.
main.py
num = 5.00 result = num % 1 == 0 print(result) # ๐Ÿ‘‰๏ธ True

The modulo (%) operator returns the remainder from the division of the first value by the second.

main.py
print(10 % 1) # ๐Ÿ‘‰๏ธ 0 print(10.5 % 1) # ๐Ÿ‘‰๏ธ 0.5

If the remainder we get from dividing the number by 1 is 0, then we have a whole number.

Conversely, if there is a remainder from dividing by 1, the number has a decimal point.

Alternatively, you can use the math.floor() method.

# Check if a float is a whole number using math.floor()

This is a three-step process:

  1. Pass the number to the math.floor() method.
  2. The math.floor() method will round the number down.
  3. Compare the rounded-down number with the number itself.
main.py
import math num = 7.00 result = math.floor(num) == num print(result) # ๐Ÿ‘‰๏ธ True
The code for this article is available on GitHub

The math.floor method returns the largest integer less than or equal to the provided number.

main.py
print(math.floor(3.99)) # ๐Ÿ‘‰๏ธ 3 print(math.floor(3.00)) # ๐Ÿ‘‰๏ธ 3

If the rounded-down number is equal to the number itself, then we have a whole number.

If the rounded-down number is different, the number has a decimal point.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev