0

I learning to do computer science and I'm stuck on this one. I made this code on python, my problem is everything is correct except when the answers are all with only one decimal point when the second on is 2. For example, I want the answer to be 17.50 when the output is given is 17.5. Is there a way I can fix this.

    amount =  float(input("Enter an amount: "))
    name = input("Enter an item name: ")
    for x in [5,10,15,20,25]:
        final= ((amount*x)/100)
        print(str(x) +"% tax on a " + str(name)+ " costing $"+ str(amount) + " is $" + str(round(final, 
        2)))
  • https://stackoverflow.com/questions/1995615/how-can-i-format-a-decimal-to-always-show-2-decimal-places See the solution about format strings: "%.2f" – ananyamous Apr 26 '20 at 02:51
  • `amount = float(...` since you are explicitly choosing to convert to a float here, you may want to read up on some of the [issues and limitations](https://docs.python.org/3/tutorial/floatingpoint.html) of floating point numbers, and how they relate to your problem here (if you are not already aware) – Hymns For Disco Apr 26 '20 at 03:01

1 Answers1

1

You can use the decimal module.

from decimal import Decimal

amount =  float(input("Enter an amount: "))
name = input("enter an item name: ")
for x in [5,10,15,20,25]:
    final= round(Decimal(amount * x / 100), 2)
    print(f"{x}% tax on a {name} costing ${amount} is ${final}")
felipe
  • 7,324
  • 2
  • 28
  • 37