How to extract the decimal part (or fractional part) of a float number in python ?

Published: April 14, 2021

Tags: Python;

DMCA.com Protection Status

Examples of how to extract the decimal part (or fractional part) of a number in python:

Using % python modulo operator

Let's consider the following float number:

import math

p = math.pi

returns

3.141592653589793

To extract the decimal part a solution is to use the modulo operator %

decimal_part = p % 1

returns

0.14159265358979312

Note:

CPU times: user 13 µs, sys: 0 ns, total: 13 µs
Wall time: 16.9 µs

Using round()

Another solution is to use round()

decimal_part = p - round(p)

returns

0.14159265358979312

Note:

CPU times: user 15 µs, sys: 0 ns, total: 15 µs
Wall time: 18.8 µs

References