Related Tags

python
float
communitycreator

# How to extract the fractional part of a float number in Python

Sarah Tanveer

In this shot, we will learn how to extract a float number’s fractional part.

The visual representation of extracting fractional part from the float.

### 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.14159265359
frac = decNum % 1
print(frac)

### 2. Using round()

#### Syntax

round(float[, decimals])


#### Parameters

The in-built function round() takes two parameters:

1. float: The float number that needs to be rounded
2. 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 int().

After rounding the float, we can take the difference between the original float and the rounded-off number to find the fractional part.

#### Code

decNum = 3.14159265359
frac = decNum - round(decNum)
print(frac)

### 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 math

decNum = 3.14159265359
frac, intNum = math.modf(decNum)

print(frac)
print("TypeError raised: ")
math.modf("5")

RELATED TAGS

python
float
communitycreator

CONTRIBUTOR

Sarah Tanveer
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time