hts95
hts95

Reputation: 123

How to round to nearest decimal in Python

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.

Upvotes: 2

Views: 1066

Answers (1)

Matthew Anderson
Matthew Anderson

Reputation: 348

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

Upvotes: 3

Related Questions