Trusted answers to developer questions

Sarah Tanveer

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

`round()`

```
round(float[, decimals])
```

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

: The float number that needs to be rounded`float`

: 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.`decimals`

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.

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

`math.modf()`

To access the function `math.modf()`

, we must first import the `math`

module.

```
math.modf(float)
```

This function takes one parameter:

- a float number.

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

Related Courses