繁体   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