Domas
Domas

Reputation: 1133

Calculation of total price when price per unit decreases with every unit jQuery

I have a jQuery slider, which captures to total amount of units ordered. The first unit's price is 50 USD. Then the price for every unit decreases by 2.66%. So the price per unit when ordering 2 would be 48,67. When ordering 3 units the price would be 47,37 per unit and so on.

I have thought of making a switch case, but that would definately be too long as the number of units may go up to 30.

I would like to as if some formula could be applied and how to do it in jQuery?

Any help is much appreciated.

Here is the slider:

  $(document).ready(function() {
      $("#slider").slider({
          range: "min",
          animate: true,
          value:1,
          min: 1,
          max: 100,
          step: 1,
          slide: function(event, ui) {
            update(1,ui.value); //changed
          }
      });

its id is "amount", and here is how i calculate the total:

$total = ($amount * $pricePerUnit) + " USD";

all that I need to get is the pricePerUnit.

Upvotes: 1

Views: 218

Answers (1)

Bucket
Bucket

Reputation: 7521

This is more of a question for https://math.stackexchange.com/, but here's what you need:

Let P be your initial price (50.00) and r be your rate of decrease (.0266). The price of unit n will be P*((1-r)^i).

When i is 0, you have your base case, which is P.

As i increments, you'll see the following pattern:

P_k = P*(1 - r)*(1 - r)*(1 - r)*...

So you can easily just raise (1 - r) to the number of units already bought, and you'll get the price for the next unit.

In jQuery, calculating this should be simple:

var baseAmount = 50.0;
var rateOfDecrease = 0.0266;
var n = $('#slider').slider("option", "value");
var pricePerUnit = baseAmount * Math.pow((1 - rateOfDecrease), n);

Upvotes: 1

Related Questions