0

I encounter small errors when calculating floats in python. Why is this?

total_sales here returns 1498.7400000000005.

sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98', '$17.41', '$28.59', '$14.51', '$19.64', '$11.40', '$8.79', '$8.65', '$10.53', '$16.49', '$6.55', '$11.86', '$22.29', '$8.35', '$2.91', '$22.94', '$4.70', '$3.59', '$5.66', '$17.51', '$5.54', '$17.13', '$21.13', '$0.35', '$13.91', '$19.26', '$5.45', '$5.50', '$14.56', '$7.33', '$20.22', '$8.67', '$8.31', '$15.70', '$6.74', '$30.84', '$12.31', '$2.94', '$22.46', '$6.60', '$6.27', '$21.12', '$2.10', '$14.22', '$11.60', '$25.27', '$8.26', '$30.80', '$22.61', '$22.19', '$7.47', '$5.49', '$23.70', '$26.66', '$25.95', '$19.55', '$15.68', '$23.57', '$29.32', '$26.44', '$17.24', '$8.49', '$13.10', '$20.39', '$14.70', '$22.45', '$28.46', '$23.89', '$24.49', '$1.81', '$6.81', '$0.65', '$26.45', '$7.69', '$8.74', '$1.86', '$14.75', '$28.10', '$9.91', '$16.34', '$27.57', '$5.25', '$9.51', '$20.56', '$21.64', '$24.99', '$29.70', '$15.52', '$15.70', '$12.36', '$13.66', '$30.52', '$22.66']

total_sales = 0
for i in sales:
  total_sales += float(i.strip("$"))
print(total_sales)
  • 1
    On a related note, you might want to look at: [Python print all floats to 2 decimal places in output](https://stackoverflow.com/questions/2075128/python-print-all-floats-to-2-decimal-places-in-output). – lurker Feb 03 '20 at 17:43
  • 1
    If you're working with financial data, you should strongly consider using the `decimal` module. – Mark Dickinson Feb 03 '20 at 18:33

0 Answers0