Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract decimal part of a floating point number

I have a function that takes a float as an input and the output is only the decimal part. For example, get_decimal(4.45) should return 0.45, and we should only return positive figures.

I made the following code:

def get_decimal(n): 
    try:
        return float('0.'+(str(n).split('.',1))[1])
    except:
        return 0

And this code almost works, but it doesn't give the whole answer. For example get_decimal(4.566666678258757587577) only returns:

0.566666678258757 

instead of:

0.566666678258757587577

Is there a way to get the whole number?

like image 595
zzz247 Avatar asked Jan 24 '23 12:01

zzz247


1 Answers

Use the modulus:

inp = 4.566666678258757587577
output = inp % 1
print(output)    # prints 0.566666678259

Note that Python's print() function usually attempts to display a more human readable form of a floating point number. So, while the printed value appears to stop after 12 digits, there is more precision beyond that not shown.

Consider:

print((output * 100000) % 1)   # prints 0.667825875724
                               #   4.566666678258757587577  <- original input
like image 150
Tim Biegeleisen Avatar answered Feb 03 '23 08:02

Tim Biegeleisen