Reputation: 85
I have this function
$("#exchange").on("change", function() {
var am = $(this).val();
var fee = $("#fee").val();
var cost = $("#cost").val();
var perc = fee / 100;
var tot = perc * am;
var fea = parseFloat(tot) + parseFloat(cost);
var total = parseFloat(am) - parseFloat(tot) - parseFloat(cost);
$("#return").val(total.toFixed(2));
$("#due").val("$" + fea.toFixed(2));
});
$("#return").on("change", function() {
var am = $(this).val();
var fee = $("#fee").val();
var cost = $("#cost").val();
var perc = fee / 100;
var tot = perc * am;
var fea = parseFloat(tot) + parseFloat(cost);
var total = parseFloat(am) + parseFloat(tot) + parseFloat(cost);
$("#exchange").val(total.toFixed(2));
$("#due").val("$" + fea.toFixed(2));
});
for example if #exchange
= 16.85, #fee
= 11, and #cost
= 0
it should calculate #due
= $1.85 and #return
= 15.00
which is all correct. The problem is working in reverse I need it to calculate the same way but instead right now I get this
#return
= 15, #fee
= 11, and #cost
= 0
it calculates #due
= $1.65 and #exchange
= 16.65
I understand why it is doing that, because it is calculating the fees from the var am
which is the value of that field, which makes it very difficult for me to accomplish what I am trying to achieve which is to make it the same both ways, but obviously I cannot call var am
to be the value of #exchange
in my #return
function because the field would be blank at that time which would calculate it at NAN
so what can I do to make it to where all of my calculations are the same both ways, I have been trying for the better part of 5 hours to figure out what to do, but I am lost, a point in the right direction would be greatly appreciated.
Upvotes: 0
Views: 249
Reputation: 4053
You are using wrong formula.
Use brutto=netto/(1-fee/100)
instead of brutto=netto*(1+fee/100)
You have to distinguish whether the fee is applied to netto (+netto*fee/100
) or to brutto (-brutto*fee/100
).
Upvotes: 1
Reputation: 346
This looks like a simple problem with your algebra to me. I see what you are trying to do. As it stands, you assume return = exchange - tot - cost
and exchange = return + tot + cost
. The problem is that you have assumed var tot
is the same in your solution working forward and your solution working in reverse.
However, tot
is equal to (fee/100) * exchange
working forward and (fee/100) * return
working backward, which breaks your assumptions for how to calculate exchange
and return
. My first step would be to move away from the var am
assignment and naming, which seems to be confusing you, and call each exchange
and return
what they really are. This might help you form a correct algebraic solution, which you can then implement in JavaScript.
JSFiddle: https://jsfiddle.net/z6hrLbmc/
Upvotes: 1