In this shot, we will learn how to extract a float number’s fractional part.
% 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.14159265359 frac = decNum % 1 print(frac)
The in-built function round() takes two parameters:
float: The float number that needs to be rounded
decimals: This is an optional argument that specifies the decimal place to which the function should round the float. If this argument is unspecified, the float will be rounded to the nearest integer.
The function will round off the float to the nearest integer value when the second argument is not given, which is equivalent to using
After rounding the float, we can take the difference between the original float and the rounded-off number to find the fractional part.
decNum = 3.14159265359 frac = decNum - round(decNum) print(frac)
To access the function
math.modf(), we must first import the
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
int is passed, the function returns a
import math decNum = 3.14159265359 frac, intNum = math.modf(decNum) print(frac) print("TypeError raised: ") math.modf("5")
View all Courses