如何在Python中四舍五入到最接近的小数

hts95

这是我第一次使用 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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章