[英]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). 我正在用Python开发一个小费计算器,现在它基本上可以工作了,只不过我想使结果的小费金额显示为2个小数,包括在必要时强制在其中加0(例如$ 8.50而不是$ 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. 我尝试搜索该问题,并认为我必须以某种方式合并%.02f,但无法弄清楚该放在哪里。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.