0

my wife and I are having troubles completing this challenge for a python course we are doing online.

The instructor says to get the result to 2 decimal spaces and when we watch the video she uses:

Example: print(round(8 / 3, 2) = 2.66

For our coding challenge we can't figure it out. This is the code in the coding challenge that we got so far. We are trying to get the 33.60 result and have been trying for two days rewriting the code.

#If the bill was $150.00, split between 5 people, with 12% tip. 

#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60

#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.

#Write your code below this line 

print("Welcome to the tip calculator.")
total_bill = input("What was the total bill? ")
tip = input("What pecentage tip would you like to give? 10, 12, or 15? ")
people = input("How many people to split the bill? ")

tip_percent = int(tip) / 100
tax_total = float(total_bill) * tip_percent
tax_and_bill = float(total_bill) + tax_total
split_cost = float(tax_and_bill) / int(people)
final_amount = round(split_cost, 2)
print(final_amount) 

Tried to rewrite the code in different ways with using what we were taught, the round(8 / 3, 2) what we were taught.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Please don't use `input()` for [mre]s on this site. Hard code some values instead. Also specify what the actual output is – Thomas Weller Jun 11 '23 at 18:33
  • 1
    What do you get instead of 33.60? What is your question? – mkrieger1 Jun 11 '23 at 18:35
  • Does this answer your question? [How to format a floating number to fixed width in Python](https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – S3DEV Jun 11 '23 at 18:49

3 Answers3

0

Use print(f"{final_amount:0.2f}") to force the formatting to include trailing zeros.

Amiel
  • 261
  • 1
  • 2
  • 7
0

The round() function in Python follows the standard rounding rules, where trailing zeros after the decimal point are not displayed by default. This behavior is because the trailing zeros are not significant for the value itself.

If you want to display the trailing zero after the decimal point, you can achieve it by formatting the number as a string using string formatting techniques. Here's an example:

final_amount = '{:.2f}'.format(split_cost)
Dejene T.
  • 973
  • 8
  • 14
0

Ignoring the inputs and just hard-coding some values gives us:

bill = 150 # total bill
people = 5 # number of people
tip = 12 # tip percentage
each = bill * (1 + tip / 100) / people

print(f'${each:.2f}')

Output:

$33.60
DarkKnight
  • 19,739
  • 3
  • 6
  • 22