toFixed
turns your number back into a string. When you +
two strings together, you get a concatenated string, like 100.9010.1
. Then you're parseFloat
ing that, which will disregard the invalid part and give you 100.901
, which you're toFixed
'ing, which rounds. I'm not sure why you'd get 100.91
for your inputs (I get 100.90
), but fundamentally those are the issues.
The solution is to pay close attention to when you're dealing with strings vs. numbers. Also, you probably don't want to hook input
on your output field (#Amount
), just your input fields.
So:
$('#AmountPaid, #OtherCharges').on('input', function() {
var AmountPaid = parseFloat($('#AmountPaid').val());
var OtherCharges = parseFloat($('#OtherCharges').val());
var Amount = AmountPaid + OtherCharges;
$('#Amount').val(Amount.toFixed(2));
});
Live Example:
$('#AmountPaid, #OtherCharges').on('input', function() {
var AmountPaid = parseFloat($('#AmountPaid').val());
var OtherCharges = parseFloat($('#OtherCharges').val());
var Amount = AmountPaid + OtherCharges;
$('#Amount').val(Amount.toFixed(2));
});
<p>Fill in either of the first two fields, and the third is updated:</p>
<label>
Amount paid:
<input type="text" id="AmountPaid" value="100.90">
</label>
<label>
Other charges:
<input type="text" id="OtherCharges" value="">
</label>
<label>
Amount:
<input type="text" id="Amount" value="">
</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
And a general caveat around using JavaScript's numbers for financial calculations: Is floating point math broken?