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

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.

相关问题 如何在 python3 中使用非常小的浮点数(例如 8.5e-350) - How to work with very small float numbers in python3 (e.g. 8.5e-350) 使用Python / tkinter在缩放(例如视网膜)显示器上显示图像 - Show images using Python/tkinter on scaled (e.g. retina) displays Python - 在打印语句中将浮点数显示为小数 - Python - show float as a decimal in a print statement 在tkinter(python 3)中,如何使程序在继续之前等待事件(例如,单击按钮)? - In tkinter (python 3) how to make the program wait for an event (e.g. button click) before continuing? Abaqus python 脚本,如何为具有多个集成点的元素(例如 C3D20R)“添加数据” - Abaqus python script, how to 'addData' for elements with multiple integration points (e.g. C3D20R) 是否可以为数字制作包装对象,例如浮动,以使其可变? - Is it possible to make wrapper object for numbers, e.g. float, to make it mutable? 你如何在情节图例中显示文本标签? (例如删除图例中的标签行) - How do you just show the text label in plot legend? (e.g. remove a label's line in the legend) plot 如何用一个图形(例如u 形)来显示面板数据回归中的非线性关系? - How to plot a graph (e.g. u-shape) to show the non-linear relationship in panel data gression? 在python 3.2中,如何比较符号,例如> - In python 3.2, how to compare a symbols e.g. > 如何将功能“附加”到 Python 中的对象,例如 Pandas DataFrame? - How to "attach" functionality to objects in Python e.g. to pandas DataFrame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM