簡體   English   中英

如何在Python中使用2個小數點顯示浮點數(例如,顯示8.60而不是8.6)

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

我正在用Python開發一個小費計算器,現在它基本上可以工作了,只不過我想使結果的小費金額顯示為2個小數,包括在必要時強制在其中加0(例如$ 8.50而不是$ 8.5)。

我嘗試搜索該問題,並認為我必須以某種方式合並%.02f,但無法弄清楚該放在哪里。

代碼如下:

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")

您可以執行以下操作以獲得兩個小數點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM