user3154990
user3154990

Reputation: 565

How to deal with NaN?

function sumOfColumns(tableID, columnIndex) {
    var tot = 0;
    $("#" + tableID + " tr").children("td:nth-child(" + columnIndex + ")").each(function () {
        tot += parseFloat($(this).html());
    });
    return tot;
}
var _totalhours = sumOfColumns("tblEmpEarnings", 3);

When I debug _totalhours is giving me NaN. Can anyone please help on this?

Upvotes: 0

Views: 138

Answers (3)

Alex W
Alex W

Reputation: 38173

NaN means "Not a Number" and is a keyword in JavaScript, not just jQuery. It is most likely the result of you trying to use parseFloat on letters instead of numbers.

How do you deal with it?

Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.

Upvotes: 7

Timigen
Timigen

Reputation: 1025

You should test the value before trying to parse it to make sure it is a number. You can use the isNaN() javascript function, NaN means Not a Number.

var tot = 0,
    value = $(this).html();

if(!isNan(value))
{
    tot += parseFloat(value);
}

Since parse float returns NaN and in javaScript NaN evaluates to false, you could also do the following:

var tot = 0,
    value = parseFloat($(this).html());

if(value)
{
    tot += value;
}

Upvotes: 1

Oriol
Oriol

Reputation: 288050

You can use 0 as a fallback value (in case the number is 0 or NaN):

tot += +$(this).html() || 0;

This way, if one value isn't numeric, you will be able to sum the other ones.

Upvotes: -1

Related Questions