The value of total_sales in step 15 seem to be incorrect

In step 15, it asks me to print total_sales and it prints out 1498.7400000000005. The same happens in the project walkthrough. However, I noticed that there isn’t any number in the list sales with more than 2 decimals. There must be a problem, but I don’t know where.

Since we are printing, then we can represent numbers as strings using string formatting.

>>> a = 1498.7400000000005
>>> print (f'{a:.2f}')    # f-string formatting
1498.74
>>> print ('{:.2f}'.format(a))    # .format() method
1498.74
>>> print ('%.2f' % a)    # modulo formatting (legacy C)
1498.74
>>> 
1 Like

I wasn’t asking about that. It’s just that since there isn’t any number with more than two decimals, it’s just impossible for their sum to have so many decimals and be 1498.7400000000005

This has something to do with the way float type values are stored in the computer’s memory. That means you do sometimes get rounding errors like this.

2 Likes

This is a really important error. It’s strange it isn’t fixed.

It isn’t an error with the CC lesson. It is the way floats are handled in the memory of a computer. Sorry, but that’s as far as my CS knowledge takes me.

It is not fixable since it is the nature of binary arithmetic. Google floating point arithmetic and see if you can come up with a solution. Hint: There is none. We need to learn how to address this in our programs. I gave you a way to represent that number as currency. Play around with other methods and see what you come up with.

2 Likes