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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With