简体   繁体   中英

How to make a float show up with 2 decimal points in Python (e.g. show 8.60 instead of 8.6)

I'm making a tip calculator in Python, and it basically works now except I want to make the resulting tip amount show up with 2 decimals, including forcing a 0 in there if necessary (so like $8.50 instead of $8.5).

I've tried searching for the problem and think I have to incorporate %.02f somehow, but can't figure out where to put it.

Code below:

bill = input("How much did your bill come out to?  ")

bill2 = float(bill.strip("$"))
#created a new 'bill2' variable to strip any $ from the input and ensure it's a float

tip15 = round (bill2 * 0.15, 4)
tip18 = round (bill2 * 0.18, 4)
tip20 = round (bill2 * 0.20, 4)

print("\nYou should tip your chosen percentage from the following...", 
    "\n\n15%: $" + str(tip15), 
    "\n18%: $" + str(tip18), 
    "\n20%: $" + str(tip20),
    "\n")

You can do the following in order to have two decimals point.

print("%.2f" % 8.5)
>>>8.50

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM