Determine if a number is an integer or a decimal in Python.
The following cases are explained with sample codes.
- Determines whether a number is an integer int or a floating-point float:
isinstance()
- Determines if a float type number is an integer (0 decimal places):
float.is_integer()
- Determines if a number string is an integer
To obtain the integer and decimal values of a decimal number, see the following article.
See the following article for information on determining whether a string is a number (including Chinese numerals, etc.) rather than whether it is an integer or decimal.
Determines whether a number is an integer or floating point type: 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'>
isinstance(object, type)
This built-in function can be used to determine if an object is of a particular type. This can be used to determine whether a number is an integer or floating point type.
print(isinstance(i, int))
# True
print(isinstance(i, float))
# False
print(isinstance(f, int))
# False
print(isinstance(f, float))
# True
In this case, it only judges the type, so it cannot judge whether a float type value is an integer (with a decimal point of 0) or not.
f_i = 100.0
print(type(f_i))
# <class 'float'>
print(isinstance(f_i, int))
# False
print(isinstance(f_i, float))
# True
Determines if a float type number is an integer (0 decimal places): float.is_integer()
The is_integer() method is provided for the float type, which 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 can be defined as follows On the other hand, a string type would be false.
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
Determines if a number string is an integer
If you want to determine that a string of integer digits is also an integer, the following functions are possible.
For values that can be converted to float type with float(), the is_integer() method is applied after the conversion to float 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 article for details on converting strings to numbers.
See the following article for details on determining whether a string is a number (including Chinese numerals, etc.).