0

I'm fairly new to Python and I came across an interesting issue when I was testing out some of the functions. Below is a snippet of the test code I'm running. My intent is to print out a price list of an item according to its weight range.

price = 0.2

for x in range(1,4):
    print("%sKG to %sKG: $%s to $%s" % ((x)*10, (x+1)*10, (x)*price, (x+1)*price))

Expected output:

10KG to 20KG: $0.2 to $0.4
20KG to 30KG: $0.4 to $0.6
30KG to 40KG: $0.6 to $0.8

Actual output:

10KG to 20KG: $0.2 to $0.4
20KG to 30KG: $0.4 to $0.6000000000000001
30KG to 40KG: $0.6000000000000001 to $0.8

The issue disappears once I change the format to "%.1f". My question is, does anyone know why are there so many decimal places in the $0.6 value?

Wb10
  • 89
  • 4
  • Side note: are you using Python 2? Either that, or your tutorial is outdated because that method of string formatting is way outdated. – Mateen Ulhaq Jan 27 '20 at 05:58
  • @MateenUlhaq I'm using python 3.8. I'm just following learnpython's guide and it uses the old format. – Wb10 Jan 27 '20 at 06:07

0 Answers0