-2

I have these two lists:

salePrices = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95]
percents = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

And then, using this for loop, I iterate through each percent and calculate the discounted price.

for percent in percents:

    for salePrice in salePrices: 
        newPrice = salePrice - ((percent / 100) * salePrice) 
        print("\t" + "{0:.2f}".format(newPrice), end = " ") 
    print()

This all works fine, except for one issue: some of the values calculated are not rounded properly.

For instance, 14.95 - (0.1 * 14.95) = 13.455, which should be rounded to 13.46 by .format(). However, the value printed is 13.45.

Is there something I am doing wrong, or is it a problem with the method, format, itself?

user2681474
  • 15
  • 1
  • 7

1 Answers1

3

Here's your problem:

14.95 - (0.1 * 14.95) = 13.455

No, in IEEE doubles, 14.95 - (0.1 * 14.95) is 13.454999999999998. Which rounds down to 13.45 correctly.

Here's the obligatory link to What Every Computer Scientist Should Know About Floating-Point Arithmetic.

If you want 14.95 to actually be exactly 14.95, rather than the closest binary fraction to 14.95, you may want to use Decimal instead of float. Of course Decimal is just as inexact, but the closest decimal fraction to 14.95 obviously really is 14.95. :)

abarnert
  • 354,177
  • 51
  • 601
  • 671