How to extract the fractional part of a float number in Python
In this shot, we will learn how to extract a float number’s fractional part.
1. Using the modulo (%) operator
The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers.
If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
Code
decNum = 3.14159265359frac = decNum % 1print(frac)
2. Using int()
The function will round off the float to the nearest integer value.
After getting the integer part of the decimal number, we can take the difference between the original float and the integer number to find the fractional part.
Code
decNum = 3.14159265359frac = decNum - int(decNum)print(frac)
In this example, int(decNum) returns 3, and subtracting it from 3.14(decNum) gives us the fractional part of the number, which is 0.14.
3. Using math.modf()
To access the function math.modf(), we must first import the math module.
Syntax
math.modf(float)
Parameters
This function takes one parameter:
- a float number.
Return value
It returns the integer and fractional parts of float as a tuple, in that order.
If some data type other than float or int is passed, the function returns a TypeError.
Code
import mathdecNum = 3.14159265359frac, intNum = math.modf(decNum)print(frac)print("TypeError raised: ")math.modf("5")
Free Resources