Python Forum

Full Version: How do I correct multiplication error? Greedy algorithm help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing a function using the greedy algorithm and with this algorithm the dollars must be converted to cents.

One of the values is 1.15, however in idle;
1.15*100
114.99999999999999

when I multiply by 100 the output is 114.99999999999999 instead of 115 which messes up the math

Is there another way to convert the dollars to cents?
There are two misunderstandings here. 
One, not all floating points can be represented perfectly accurately by computers. 
Read more here to understand this issue:  
https://en.wikipedia.org/wiki/Floating-point_arithmetic

The second is that this is mostly a display issue:
>>> 1.15*100
114.99999999999999
>>> print(1.15*100)
115.0
>>>
In terms of money it is often best to do all calculations in cents until the end.

Converting dollars to cents you have a couple options, use the decimal module
>>> from decimal import Decimal
>>> a = Decimal("1.15")
>>> a * 100
Decimal('115.00')
>>>
Or in this case you can probably just use round.
>>> int(round(1.15*100))
115
>>>