How to round to nearest decimal in Python

对着背影说爱祢 提交于 2021-02-10 15:36:26

问题


This is my first time working with Python. I'm trying to figure out how to round decimals in the simplest way possible.

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))

I need it to look like this image.


回答1:


You should use Python's built-in round function.

Syntax of round():

round(number, number of digits)

Parameters of 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.

Therefore, you should try code more like:

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))


来源:https://stackoverflow.com/questions/57011481/how-to-round-to-nearest-decimal-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!