0

I'm a newbie when it comes to Python, so please forgive me for this stupid question however, here it is :D The following code is just for practice for my Python course. The source code can be found here: https://pastebin.com/46CfQzhu

The output would vary based on the number of people and the type of activity. Every single test works, except when I assign 20 for junior, 20 for senior and the activity to be cross-country. According to the problem's description, when those number are used, the end result should be 377.63. However I get 377.62. I need to format the number to .2f, however that doesn't give me the right value at the end. Tried round() and it was still a no go. The number is actually 377.625 and it should round up to 377.63.. Any thoughts on the matter? Thanks!

PS I'm copying the code here, for better visibility.

tax = round(tax,2)
print(f'{tax:.2f}')
junior = int(input())
senior = int(input())
trace = input()
 
tax=0
 
if trace == 'trail':
    tax = junior * 5.50 + senior * 7
elif trace =='cross-country':
    if (junior + senior) >= 50:
     tax = (junior * 8 + senior * 9.50) * 0.75
    else:
        tax = junior * 8 + senior * 9.50
elif trace =='downhill':
    tax = junior *12.25 + senior * 13.75
elif trace =='road':
    tax = junior * 20 + senior*21.50

tax = tax*0.95
tax = round(tax,2)
print(f'{tax:.2f}')
  • 1
    Does this answer your question? [How to round to 2 decimals with Python](https://stackoverflow.com/questions/20457038/how-to-round-to-2-decimals-with-python) – Nastor Nov 11 '20 at 14:09

1 Answers1

1

Please next time you post a question be more specific. Your problem is just a mere round problem and the other details are not relevant. You could have just asked why following code behaves as such,

tax = round(377.625, 2)
print(f'{tax:.2f}')

> 377.62

And you would have easily reached the below solution if you searched for 5 mins. Google is your best friend. :)

https://docs.python.org/3/library/functions.html#round

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

BcK
  • 2,548
  • 1
  • 13
  • 27
  • should also mention that *if it is representable*, python will round half to the even choice - `if two multiples are equally close, rounding is done toward the even choice` – Chase Nov 11 '20 at 14:29
  • Thank you! :) will be more specific next time. Have a great one ! – Petya Petkova Nov 11 '20 at 15:43
  • @PetyaPetkova and when your problem is solved, don't forget to mark it as solved. – BcK Nov 11 '20 at 16:15