0

The total price inclusive of tax is 5 (which includes 10% tax) which means actual price is 4.55

and tax is 0.45
but if i do
10/100x4.55 it gives 0.46 (rounding to 2 points)
and total becomes
4.55+0.46=5.01 (actually should be 5.00)

so what can I do?

var tax_amount = ((parseFloat(actual_amount)*parseFloat(tax_percent))/parseFloat(100)).toFixed(2);

for 4.55 it produces 0.45555 which becomes 0.46 which should be 0.45 actually.

If i truncate it will be problem for another cacluations 0.4577 indeed should be 0.46

mplungjan
  • 169,008
  • 28
  • 173
  • 236
TheGooooogle
  • 263
  • 3
  • 11
  • 1
    For financial calculations, regardless weather you are using javascript, C++, Swift, go etc. you should use integers and calculate cents, not dollars. You can format your currency as dollars for display but only for display and parse user input by removing the decimal point as a string – slebetman Mar 08 '19 at 07:31
  • @slebetman that's certainly true, but you are still left with the same rounding problem: 455 + .1 * 455 = 500.5 which the OP is having trouble with. – Mark Mar 08 '19 at 07:32
  • 2
    It's not clear why you think `0.45555` should result in a tax of `0.45` and not `0.46`. – Mark Mar 08 '19 at 07:34
  • Agree with @MarkMeyer. Can you calculate it with: totalPrice-priceWithoutTax? – jare25 Mar 08 '19 at 07:38
  • @mark Meyer The user will just enter final price which is inclusive of tax, For example, $5 and We need to show how much was the actual price and how much was the tax. it is x+10% of x=5$. So, how much is actual price and how much is the tax in 5$? mathematically rounding to 2 decimal points, 4.55+0.46 makes 5.01 which is not a blunder but still a mistake. So what can i do? – TheGooooogle Mar 08 '19 at 10:26
  • @TheGooooogle you need to solve the equation: `final_price = price + price * tax` for `price`. This gives you `price = final_price / (1 + tax)`. For a 1% tax and a final price of $5.00 your price will be `4.545454545454545...` – Mark Mar 08 '19 at 11:34

0 Answers0