5

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;
}
user3314032
  • 179
  • 10

1 Answers1

7

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;
}
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474