methuselah methuselah - 6 months ago 16
Javascript Question

Incorrect Javascript math result, removing NaN message

I'm trying to run the following sum in JavaScript


(a + b) - c


but unfortunately I keep getting the following result (example sun):


(25 + 25) - 1

= 2524


here is the code im using at the moment

<script>
$(document).ready(function(){
$('#previousRent').change(function(){
calcResult();
});
$('#rentPaid').change(function(){
calcResult();
});
$('#wRun').change(function(){
calcResult();
});
});
function calcResult() {
$('#result').val( parseFloat($('#previousRent').val() + parseFloat($('#wRun').val()) - $('#rentPaid').val()) );
}
</script>


Does anyone know how to get rid of the NaN that appears when all fields are not filled?

Answer

I would do something like this, in case the fields aren't populated:

function calcResult() {  
 $('#result').val(
  (parseFloat($('#previousRent').val()||"0") + parseFloat($('#wRun').val()||"0"))
    - parseFloat($('#rentPaid').val()||"0"));  
} 

This would treat any empty field as 0 instead of throwing a NaN calculation error. Or, a bit cleaner version:

function getVal(sel) { return parseFloat($(sel).val()||"0"); }
function calcResult() {  
  $('#result').val(getVal('#previousRent') + getVal('#wRun') - getVal('#rentPaid'));  
}