2

I am very new to this so the code is really simple, and the result I get when I print is 1498.7400000000005. Can anyone help me figure out why I get all those extra 0s and 5s?

Listy = [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.4, 8.79, 8.65, 10.53, 16.49, 6.55, 11.86, 22.29, 8.35, 2.91, 22.94, 4.7, 3.59, 5.66, 17.51, 5.54, 17.13, 21.13, 0.35, 13.91, 19.26, 5.45, 5.5, 14.56, 7.33, 20.22, 8.67, 8.31, 15.7, 6.74, 30.84, 12.31, 2.94, 22.46, 6.6, 6.27, 21.12, 2.1, 14.22, 11.6, 25.27, 8.26, 30.8, 22.61, 22.19, 7.47, 5.49, 23.7, 26.66, 25.95, 19.55, 15.68, 23.57, 29.32, 26.44, 17.24, 8.49, 13.1, 20.39, 14.7, 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.1, 9.91, 16.34, 27.57, 5.25, 9.51, 20.56, 21.64, 24.99, 29.7, 15.52, 15.7, 12.36, 13.66, 30.52, 22.66]

sum_of_list = 0 

for num in listy: 

    sum_of_list += num

print(sum_of_list)

>>> 1498.7400000000005
coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • You're doing nothing wrong – roganjosh Nov 22 '20 at 21:59
  • This is just the nature of representations of decimal numbers in programming languages. You can see the problem very quickly just by doing 0.1 + 0.11. I would advise that if you want to not lose any information, you multiply all numbers by 100, removing the decimal, then you will not experience such issues. – Countingstuff Nov 22 '20 at 22:00
  • You're doing nothing wrong - except that with a fixed precision like this you should store the numbers as integers and divide by 100 in the end, or use `Decimal` module – Jean-François Fabre Nov 22 '20 at 22:01
  • maybe this can help you: https://stackoverflow.com/questions/8568233/how-to-print-float-to-n-decimal-places-including-trailing-0s – Joaquín Nov 22 '20 at 22:01

1 Answers1

1
  • You can just use sum
  • you can round the number to what ever dcp you like
Listy = [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.4, 8.79, 8.65, 10.53, 16.49, 6.55, 11.86, 22.29, 8.35, 2.91, 22.94, 4.7, 3.59, 5.66, 17.51, 5.54, 17.13, 21.13, 0.35, 13.91, 19.26, 5.45, 5.5, 14.56, 7.33, 20.22, 8.67, 8.31, 15.7, 6.74, 30.84, 12.31, 2.94, 22.46, 6.6, 6.27, 21.12, 2.1, 14.22, 11.6, 25.27, 8.26, 30.8, 22.61, 22.19, 7.47, 5.49, 23.7, 26.66, 25.95, 19.55, 15.68, 23.57, 29.32, 26.44, 17.24, 8.49, 13.1, 20.39, 14.7, 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.1, 9.91, 16.34, 27.57, 5.25, 9.51, 20.56, 21.64, 24.99, 29.7, 15.52, 15.7, 12.36, 13.66, 30.52, 22.66]

summ = sum(Listy)
print(round(summ,2))

>>> 1498.74
coderoftheday
  • 1,987
  • 4
  • 7
  • 21