When I am running this, it returns NaN
. If I do not parseFloat, I'm getting 2 strings added. What am I missing? I would say that my result should always be a float?
function calculate(i) {
var result = 0.0;
$j(".t" + i + " input").each(function () {
var number = $j(this).val();
number = number.replace(",", ".");
if (parseFloat(number) != NaN) {
result = parseFloat(result);
number = parseFloat(number);
result += number;
}
});
console.log(result);
return result;
}
You're not validating not a number correctly. To check if a number is NaN
use the isNaN
function:
if (!isNaN(parseFloat(number))) { ... }
Note that NaN === NaN
returns false
always.
You can read more about this here: Why is NaN === NaN false?
Here is the complete code:
function calculate(i) {
var result = 0;
$j(".t" + i + " input").each(function () {
var number = $j(this).val();
number = parseFloat(number.replace(",", "."));
if (isNaN(number)) {
return;
}
result += number;
});
console.log(result);
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With