In this shot, we will learn how to extract a float number’s fractional part.
%
) operatorThe %
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.
decNum = 3.14159265359frac = decNum % 1print(frac)
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.
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.
math.modf()
To access the function math.modf()
, we must first import the math
module.
math.modf(float)
This function takes one parameter:
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.
import mathdecNum = 3.14159265359frac, intNum = math.modf(decNum)print(frac)print("TypeError raised: ")math.modf("5")