The modf() function of math, the standard module for mathematical functions in Python, can be used to obtain the integer and decimal parts of a number simultaneously.
See the following article for divmod(), which simultaneously obtains the quotient and remainder of a division.
Get integer and decimal parts without math module
Applying int() to a floating-point float type yields an integer value with the decimal point truncated. This can be used to obtain the integer part and the decimal part.
a = 1.5
i = int(a)
f = a - int(a)
print(i)
print(f)
# 1
# 0.5
print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>
Get integer and decimal parts of a number simultaneously with math.modf()
The function modf() in the math module can be used to simultaneously obtain the integer and decimal parts of a number.
math.modf() returns the following tuple Note the order, since the decimal part comes first.
(decimal, integer)
import math
print(math.modf(1.5))
print(type(math.modf(1.5)))
# (0.5, 1.0)
# <class 'tuple'>
Each can be unpacked and assigned to a separate variable as follows Both integer and decimal parts are float types.
f, i = math.modf(1.5)
print(i)
print(f)
# 1.0
# 0.5
print(type(i))
print(type(f))
# <class 'float'>
# <class 'float'>
The sign will be the same as the sign of the original value for both integer and decimal parts.
f, i = math.modf(-1.5)
print(i)
print(f)
# -1.0
# -0.5
Applicable to int types. In this case, both integer and decimal parts are float types.
f, i = math.modf(100)
print(i)
print(f)
# 100.0
# 0.0
The following method can be used to check whether a float type is an integer (i.e., the decimal part is 0) without obtaining the decimal part. See the following article.
float.is_integer()