Get the Fractional and Integer Parts in Python: math.modf()
The math.modf()
function allows you to get both the fractional and integer parts of a number simultaneously.
For a function that returns the quotient and remainder, check out the following article on divmod()
.
Get fractional and integer parts using math.modf()
The math.modf()
function enables you to get both the fractional and integer parts of a number at once.
math.modf()
returns a tuple in the format (fractional part, integer part)
.
import math
print(math.modf(1.5))
print(type(math.modf(1.5)))
# (0.5, 1.0)
# <class 'tuple'>
You can assign each part to a variable using unpacking. Both the fractional and integer parts are of the float
data type.
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 of the parts will match that of the original value.
f, i = math.modf(-1.5)
print(i)
print(f)
# -1.0
# -0.5
math.modf()
can also be applied to the int
. Again, both the fractional and integer parts are float
.
f, i = math.modf(100)
print(i)
print(f)
# 100.0
# 0.0
To check if a float
is an integer (meaning the fractional part is 0), you can use the is_integer()
method for float
without obtaining the fractional part. See the following article for more information.
Get fractional and integer parts without math module
By applying int()
to a floating-point number, you can get its integer part. Consequently, you can extract both the fractional and integer parts.
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'>