Issue
I have the following code in python,
x = 0.29
x = int(x*100)
print(x)
It prints 28, and this is causing an infinite loop in my code. How do I resolve this issue? I think this is some machine precision issue. I my program I want the value of int(x*100) to be 29.
Solution
You're encountering a floating-point precision issue, try using the Decimal
library which is designed to give better precision with floating-point numbers:
from decimal import Decimal
x = Decimal('0.29')
x = int(x * 100)
print(x)
Should output 29
as you expect.
As per OP comment:
from decimal import Decimal
def get_float():
return 0.29 # Simulating the function that returns a float
x = int(Decimal(str(get_float())) * 100)
print(x)
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.