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();
});
$('#rentPai开发者_C百科d').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?
I think you should re-arrange the parentheses a bit:
function calcResult() {
$('#result').val( (parseFloat($('#previousRent').val()) + parseFloat($('#wRun').val())) - $('#rentPaid').val() );
}
Edit: Some explanation: Note that the val() function returns the value of the element, which is a string. In javascript the "+"-operator is used for concaterating strings which means that you are sending in "2525" to the first parseFloat-call..
You have a problem with brackets. This is the right line:
$('#result').val( parseFloat($('#previousRent').val()) + parseFloat($('#wRun').val()) - parseFloat($('#rentPaid').val()) );
changes function calcResult() with below content
function calcResult() {
$('#result').val(parseFloat($('#previousRent').val()) + parseFloat($('#wRun').val()) - parseFloat($('#rentPaid').val()));
}
You are trying to add strings, which concatenates them. I don't know jQuery but you need to make sure your variables end up as integer or float values so it can evaluate the match, not the strings.
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'));
}
No need to use the brackets when you are just using (24+24)-1
Just use like this 24+24-1
pasrse each string to float separatly
You have used
$('#result').val(
parseFloat($('#previousRent').val()
+ parseFloat($('#wRun').val())
- $('#rentPaid').val()) );
Use this
$('#result').val(
parseFloat($('#previousRent').val())
+ parseFloat($('#wRun').val())
- parseFloat($('#rentPaid').val()) );
精彩评论