note.nkmk.me

Check if a number is integer or decimal in Python

Posted: 2019-09-16 / Tags: Python

How to check (determine) whether a number is integer or decimal in Python is explained with sample code in the following cases.

  • Check if object is int or float: isinstance()
  • Check if float is integer: is_integer()
  • Check if numeric string is integer

If you want to get velues of the fractional and integer parts, see the following post.

Sponsored Link

Check if object is int or float: isinstance()

The type of an object can be obtained with the built-in function type().

i = 100
f = 1.23

print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>

The built-in function isinstance(object, type) can be used to determine whether an object is of a particular type.

print(isinstance(i, int))
# True

print(isinstance(i, float))
# False

print(isinstance(f, int))
# False

print(isinstance(f, float))
# True

In this case, since only the type is checked, it cannot be determined whether the value of float is an integer (the fractional part is 0).

f_i = 100.0

print(type(f_i))
# <class 'float'>

print(isinstance(f_i, int))
# False

print(isinstance(f_i, float))
# True

Check if float is integer: is_integer()

float has is_integer() method that returns True if the value is an integer, and False otherwise.

f = 1.23

print(f.is_integer())
# False

f_i = 100.0

print(f_i.is_integer())
# True

For example, a function that returns True for an integer number (int or integer float) can be defined as follows. This function returns False for str.

def is_integer_num(n):
    if isinstance(n, int):
        return True
    if isinstance(n, float):
        return n.is_integer()
    return False

print(is_integer_num(100))
# True

print(is_integer_num(1.23))
# False

print(is_integer_num(100.0))
# True

print(is_integer_num('100'))
# False
Sponsored Link

Check if numeric string is integer

If you want to determine that the string of integer numbers is also an integer, the following function can be considered.

If possible, the value is converted to float with float(), then is_integer() method is called and the result is returned.

def is_integer(n):
    try:
        float(n)
    except ValueError:
        return False
    else:
        return float(n).is_integer()

print(is_integer(100))
# True

print(is_integer(100.0))
# True

print(is_integer(1.23))
# False

print(is_integer('100'))
# True

print(is_integer('100.0'))
# True

print(is_integer('1.23'))
# False

print(is_integer('string'))
# False

See the following posts for details on converting strings to numbers and handling exceptions with try ... except ....

Sponsored Link
Share

Related Categories

Related Posts