usama - 1 year ago 44

Javascript Question

hi i am creating a percentage calculation like upwork use on his own site

the percentage calculation is working fine when i am calculating the percentage from base amount

Percentage is 10%

Let say for base amount

`89.00`

`8.90`

`80.10`

here is the code for this

`$('txtclientBid').on('input', function() {`

var clientRate = parseFloat($(this).val()) || 0;

var num = parseFloat(clientRate) || 0;

// $discount_value = ($total / 100) * $percent;

var val = (num - (num * .1)).toFixed(2);

var fee= (num /100) * 10;

$(settings.txtcarrierRate).val(val);

$('.siteFee').val('-'+fee.toFixed(2))

});

but when i calculate the base amount from the estimated amount then i get different values

For example using the same above scenario if i type

`80.10`

`8.01`

`88.11`

can some one please tell me why i am getting different values in both cases

Case 2 is not working fine

here is my code for this

`$('.txtbidderRate').on('input', function() {`

var carrierRate = parseFloat($(this).val()) || 0 ;

var num = parseFloat(carrierRate) || 0;

var val = (num + (num * .1)).toFixed(2);

var fee= (num /100) * 10;

$(settings.txtclientRate).val(val);

$('.siteFee').val('-'+fee.toFixed(2))

});

Kindly help me on this

Answer Source

This is math.

Say base amount is 100. 10% of 100 = 10. After deduction, 100-10 = 90.

i.e.

```
Estimated Amount = Base Amount - 0.1*Base Amount = 0.9*Base Amount
```

Now consider the other case. You want to get back 100 from the 90 i.e you want to get the base amount from the estimated amount.

So, from the above equation,

```
Base Amount = Estimated Amount/0.9
```

i.e. Base Amount = 90/0.9 = 100.

You are trying to apply the same equation for both the cases - which obviously won't work.

I hope this is what you misunderstood.

So I guess your second `val`

should be calculated this way:

```
val = (num/0.9).toFixed(2);
```

EDIT:

Okay let's make things simple. Say you have $89 - this is your base amount. According to what you have written,

```
Estimated Amount = Base Amount - 10% of Base Amount
```

which basically means

```
Estimated Amount = 100% of Base Amount - 10% of Base Amount = 90% of Base Amount
```

So,

```
Estimated Amount = 90% of Base Amount = (90/100)*Base Amount = 0.9*Base Amount
```

Now think the other way round, you have the `Base Amount`

and you want the `Estimated Amount`

. How would we get it ?

Since `Estimated Amount = 0.9*Base Amount`

, we can say `Base Amount = Estimated Amount/0.9`

(Dividing both sides by 0.9)

So from your $89,

Estimated Amount = 0.9*89 = $80.1

Now suppose you are given Estimated Amount i.e $80.1, and we need to find Base Amount

We know that `Base Amount = Estimated Amount/0.9`

from above, so we have

```
Base Amount = 80.1/0.9 = $89
```

Hope this helps.