Extract decimal part of a floating point number

Viewed 239

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?

3 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

you can try this :

output = round(inp-int(inp),abs(decimal.Decimal(str(inp)).as_tuple().exponent)

you can use Decimal but in that case you need to set your input as string:

from decimal import *

def get_decimal(n): 
    try:
        return Decimal('0.'+(str(n).split('.',1))[1])
    except:
        return 0
print(get_decimal("4.5666666782587575875779"))

output:

0.5666666782587575875779
Related