-1

I’m writing a simple program and I’m using .format() to round the number to 2 d.p.

 State = 0.05
 County = 0.025
 Purchase = float(input(‘amount of purchase: ‘))
 State_tax = purchase * state
 County_tax = purchase * county
 Total_tax = state_tax + county_tax
 Total = purchase + total_tax
 Print(‘amount: ‘ + ‘{:.2f}’.format(purchase))
 Print(‘state tax: ‘ + ‘{:.2f}.format(state_tax))
 Print(‘county tax: ‘ + ‘{:.2f}.format(county_tax))
 Print(‘total tax: ‘ + ‘{:.2f}.format(total_tax))
 Print(‘total sale: ‘ + ‘{:.2f}.format(total))

To test it I inputted 11. However, the total doesn’t add up correctly to the tax. The total tax is 0.83 but the total is 11.82. It doesn’t round 11.825 to 11.83. How could I fix this?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Python uses banker's rounding, which rounds 5 to the even number, regardless of whether it is larger or smaller. You will notice `'{:.2f}'.format(11.835)` results in 11.84. – alec Feb 21 '20 at 10:19
  • Does this answer your question? [How can I get more exact decimal values in Python](https://stackoverflow.com/questions/32613997/how-can-i-get-more-exact-decimal-values-in-python) – Jongware Mar 02 '20 at 13:53

2 Answers2

0

Python usually round to min value if fraction value is less than or equal to 5, It rounds up to max value when the fraction value is above 5.

You can even try this to round the number

print("amount: {}".format(round(purchase, 2)))

To round the amount to 2 digits

0

Because you are calculating tax total without formatting Try this one for tax as you shown in print

total_tax = float('{:.2f}'.format(state_tax)) + float('{:.2f}'.format(county_tax))

This fix fix your total