0

Is it possible to apply a tax for a certain quantity?
For example:

1: 0% tax
2-5: 5% tax
6-10: 10% tax
11-15: 15 % tax
16-20: 20 % tax

The problem is that the function always applies 5% tax for every quantity.
If a tax is applied, then the total should update, and calculate the tax and final total from there.

var tax = Math.round(price * 0.05 * 100) / 100
David
  • 6,695
  • 3
  • 29
  • 46
  • 3
    Did you try to use a switch statement and do your calculations inside the switch? – Mohammed Oct 08 '18 at 05:42
  • 1
    Please see [*How to create a minimal, complete and verifiable example*](https://stackoverflow.com/help/mcve) and reduce your code to the minimum required to display the issue. Also, you do three rounding operations in a row, which is a bad idea. Do all the mathematics first, then round only at the very end since simple rounding is biased upward. – RobG Oct 08 '18 at 05:44
  • I updated the snippet so you can understand better. – Emanuel Santos Oct 08 '18 at 06:08
  • @RobG - good point about including a *MCVE* (I have edited the question). But regarding the round operations, normally you pay (rounded) taxes for the (already rounded) price that you charge. Maybe in this case both operations are necessary. What you don't need is to round the final price. – David Oct 08 '18 at 07:24

2 Answers2

1

You can use a switch statement.

Wrap it up in a function together with the round logic:

function getTax( price ){
  var taxRate = 0;
  switch( true ){
    case ( price < 2 ):
    // or case ( price <= 1 ) depending on what you need
      break;
    case ( price < 6 ):
      taxRate = 0.05;
      break;
    case ( price < 11 ):
      taxRate = 0.1;
      break;
    case ( price < 16 ):
      taxRate = 0.15;
      break;
    default:
      taxRate = 0.2;
  }
  return Math.round( price * taxRate * 100 ) / 100;
}

And then call the function to get the returned value:

var tax = getTax( price );

switch( true ) can be a confusing usage of this statement and not everyone like it. You can read about it here and here. Go for if statements if you prefer it.

Also, beware of some caveats regarding the Math.round function.

David
  • 6,695
  • 3
  • 29
  • 46
0

As far as I can see, you are using a hardcoded tax.

var tax = Math.round(price * 0.05 * 100) / 100

Here, in the changeTotal function, you should be using your desired tax value instead of simply multiplying by 0.05.