Float() returns strange decimals

Hello, while doing the ‘thread shed’ project ( https://www.codecademy.com/paths/computer-science/tracks/cspath-python-objects/modules/cspath-python-strings/projects/thread-shed ) something unexpected happened at point 14: i’m going through a list of strings like '$1.40', removing the '$', converting them to floats and adding them up.

for i in sales:
  total_sales += float(i.strip('$'))

the float conversion seems to be working out fine but for some reason, at certain points, the function doesn’t seem to be adding them correctly to the variable (e.g. for the ‘157.7 + 19.64’ calculation i get 177.33999999999997 as a result instead of 177.34).
I get 316.39000000000004 at the end, when all the floats have only 2 decimal places.

It’s just a floating point error because the value cannot be that precise. You could look at the Decimal module for Python which allows you to work with decimal points.
A relevant question/answer-

2 Likes

If you’re counting cents you can use int

3 Likes