-5

I am a beginner programmer and this is a small program. I want my final output variable per_person to have exactly 2 decimal places. Why is this not happening with my code? When I write that the total bill is 150 and the number of people is 5, the final answer is 33,6, however I want it to be 33,60.

bill = input("Can you tell us how much is the total bill?: ")
final_bill = int(bill) * 1.12
print(type(final_bill))
number_of_people = input("How many people are we?: ")
per_person = round(final_bill / int(number_of_people), 2)
print(per_person)

I expected that by printing the per_person variable I would get something with 2 decimal places, however it is always one.

Timus
  • 10,974
  • 5
  • 14
  • 28
merkogk
  • 1
  • 1
  • 2
    A *value* being rounded to 2 places is different from *printing* 2 decimal places. – Scott Hunter May 10 '23 at 12:32
  • `print(f"{per_person:.2f}")` – not_speshal May 10 '23 at 12:35
  • You might need to use `final_bill = float(bill) * 1.12` unless the bill is always integral. – jarmod May 10 '23 at 12:36
  • 1
    @9769953: Documentation of *what*? How is that related to the difference between changing a value & how it is displayed? – Scott Hunter May 10 '23 at 12:38
  • If this is not a question about _displaying_ (printing) a float with 2 decimal places but about actually calcuating with exactly 2 decimal places, then you should look into the [`demcimal`](https://docs.python.org/3.11/library/decimal.html) module of the standard library. – Timus May 10 '23 at 14:42

1 Answers1

-1

Like everyone said, being rounded to 2 decimal places is not the same as printing 2 decimal places. After all, python doesn't know you are dealing with money here, so its going to print the value to a sufficient degree of accuracy, not what is socially expected (for currency, time etc). To fix it, just add a formatting command after the per_person calculation, with ".2f" indicating 2 flaoting point == decimal places :

bill = input("Can you tell us how much is the total bill?: ")
final_bill = int(bill) * 1.12
print(type(final_bill))
number_of_people = input("How many people are we?: ")
per_person = round(final_bill / int(number_of_people), 2)
rounded_per_person=format(per_person, ".2f")
print(rounded_per_person)
Learn4life
  • 227
  • 1
  • 8