Python float - Get integer and fractional parts

Here is how to get the integer and fractional parts of a float.

n = 3.14

i = int(n)
f = n - i

print(i)  # 3
print(f)  # 0.14000000000000012

It's so primitive. The fractional part has many 0s and it is negative when the number is negative as follows.

n = -7.8

i = int(n)
f = n - i

print(i)  # -7
print(f)  # -0.7999999999999998

Using math.modf()

The Python standard library has a simple method to split a float into the integer and fractional parts.

import math

n = 3.14
a = math.modf(n)
f, i = math.modf(n)

print(a)  # (0.14000000000000012, 3.0)
print(f)  # 0.14000000000000012
print(i)  # 3.0

The modf() in math module returns a tuple of the fraction and integer parts. It splits a negative float into the negative integer and negative fractional parts.

import math

n = -2.58
a = math.modf(n)
f, i = math.modf(n)

print(a)  # (-0.5800000000000001, -2.0)
print(f)  # -0.5800000000000001
print(i)  # -2.0

Python Float

Python Tutorial