python - 如何在Python中四舍五入到最接近的小数
问题描述
这是我第一次使用 Python。我试图弄清楚如何以最简单的方式舍入小数。
print("\nTip Calculator")
costMeal = float(input("Cost of Meal:"))
tipPrct = .20
print("Tip Percent: 20%")
tip = costMeal * tipPrct
print("Tip Amount: " + str(tip))
total = costMeal + tip
print("Total Amount: " + str(total))
解决方案
您应该使用Python 的内置 round 函数。
round() 的语法:
round(number, number of digits)
round() 的参数:
..1) number - number to be rounded
..2) number of digits (Optional) - number of digits
up to which the given number is to be rounded.
If not provided, will round to integer.
因此,您应该尝试更多类似的代码:
print("\nTip Calculator")
costMeal = float(input("Cost of Meal: "))
tipPrct = .20
print("Tip Percent: 20%")
tip = costMeal * tipPrct
tip = round(tip, 2) ## new line
print("Tip Amount: " + str(tip))
total = costMeal + tip
print("Total Amount: " + str(total))
推荐阅读
- python-3.x - 为什么以下代码的代码显示 NameError
- python - 无法使用 python 打开数据库 [Microsoft] [ODBC Driver 13 for SQL Server]
- javascript - 如果在页面中找到文本,则自动单击按钮
- api - DocuSign API 与 RESTful Web 服务的集成问题:javax.ws.rs-api-2.0.1.jar
- java - 如何将文本文件中的不同列复制到变量中
- system-verilog - 如何在 systemverilog 中转换为 longint unsigned?
- javascript - Chart.js 点击事件打开自定义工具提示有时不起作用
- spring - Spring Batch - 根据条件循环回任何上一步
- swift - 有谁知道如何让它工作我正在尝试使用 pagecontrol 制作幻灯片,但索引显示错误
- floating-point - 手动将 Double 转换为 Float,反之亦然