note.nkmk.me

Get the fractional and integer parts with math.modf() in Python

Posted: 2019-09-16 / Tags: Python

math.modf() can be used to get the fractional and integer parts of a number simultaneously.

See the following post for divmod() which return the quotient and remainder.

Sponsored Link

Get the fractional and integer parts without math module

Applying int() to the floating-point number float, you can get the integer part.

Using this, the fractional and integer parts can be obtained.

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'>
source: math_modf.py

Get the fractional and integer parts with math.modf()

modf() in the math module can be used to get the fractional and the integer parts of a number at the same time.

math.modf() returns a tuple (fractional part, integer part).

import math

print(math.modf(1.5))
print(type(math.modf(1.5)))
# (0.5, 1.0)
# <class 'tuple'>
source: math_modf.py

Each can be assigned to a variable using unpacking. Both the fractional and the integer parts are float.

f, i = math.modf(1.5)

print(i)
print(f)
# 1.0
# 0.5

print(type(i))
print(type(f))
# <class 'float'>
# <class 'float'>
source: math_modf.py

The sign is the same as the original value.

f, i = math.modf(-1.5)

print(i)
print(f)
# -1.0
# -0.5
source: math_modf.py

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
source: math_modf.py

Whether float is an integer (the fractional part is 0) can be checked with float method is_integer() without obtaining the fractional part. See the following article.

Sponsored Link
Share

Related Categories

Related Posts