Home > OS >  Float Place Holder Prints Extra Zeroes
Float Place Holder Prints Extra Zeroes

Time:12-13

Here's an excerpt of my code:

elif choice == "3":
    print("====================================\nPRINTING LIST...")
    #prints in this format: item name              item price      item quant and accesses the keys
    for i in glist:
        print("%s              %f              %d" %(i["item"], i["price"], i["quant"]))

Basically, what the program does is ask the user for an item, price of the item, and it's quantity stores it in a dictionary and prints it in a formatted format. When the user chooses 3, it should execute the aforementioned blocks of code.

The expected outcome should go something like this: USER INPUT: Item: Egg Price: 2 Quant: 3

EXPECTED RESULTS: Egg 2.00 3

The result I am getting: USER INPUT: Item: Egg Price: 2 Quant: 3

EXPECTED RESULTS: Egg 2.0000000000 3

How do I remove the excess zeros in the item price?

I haven't tried anything yet because I am clueless on what it is I should do.

CodePudding user response:

for i in glist:
    # Use the format method to specify the number of decimal places to display
    print("{:<20} {:<10.2f} {:<10d}".format(i["item"], i["price"], i["quant"]))

CodePudding user response:

You can use %0.2f in print function

For example

elif choice == "3":
    print("====================================\nPRINTING LIST...")
    #prints in this format: item name              item price      item quant and accesses the keys
    for i in glist:
        print("%s              %0.2f              %d" %(i["item"], i["price"], i["quant"]))

This code giving Egg 2.00 3

  • Related