Home > Software engineering >  Why is the number of decimals not correct when I truncate it to 2 and why isn't it the correct
Why is the number of decimals not correct when I truncate it to 2 and why isn't it the correct

Time:07-11

I need help with this function.

def expenses(monthly_budget):
    expenses = float(input("What are your actual expenses each month? "))
    perc_act_expenses = expenses / monthly_budget
    perc_act_expenses = round(perc_act_expenses, 2)
    print(f"Your actual expenses are {expenses} and that is {perc_act_expenses * 100}% of your monthly budget.") 
    rec_expenses = .50 * monthly_budget
    rec_expenses = round(rec_expenses, 2)
    print(f"Recommended amount spent on expenses each month is ${rec_expenses}\n")

When I put 100000 as the salary and calculate the net income after fed and state tax for FL I get 85000. The monthly budget is 85000/12 = 7083.33

This is what I get as the output: What are your actual expenses each month? 8000 Your actual expenses are 8000.0 and that is 112.99999999999999% of your monthly budget. Recommended amount spent on expenses each month is $3541.66

-It should only round to 2 decimal points and it doesn't -I'm expecting an output of 112.94

What am I doing wrong?

CodePudding user response:

When you did the first rounding of perc_act_expenses, you have already lost some precision, and so when you multiply that with 100, it won't be as exact (also, you're not rounding the result of the multiplication). You should calculate the percentage first, and then round it like so:

>>> expenses = 8000.0
>>> monthly_budget = 7083.33
>>> round(100 * expenses / monthly_budget, 2)
112.94

Also, since you're using f-strings, you could round with them like so:

>>> print(f'Your actual expenses are {expenses:.2f} and that is {100 * expenses / monthly_budget:.2f}% of your monthly budget.')
Your actual expenses are 8000.00 and that is 112.94% of your monthly budget.
  • Related