Skip to content Skip to sidebar Skip to footer

Getting Nan If Variable Has Null Value

Here, I am getting record through ajax and json. I am getting value if the variable have. But, If variable 'performance' have null value, it shows NaN. Instead of NaN, I want to pr

Solution 1:

Use an OR operator to set the number to zero.

var total_month_earn = data.total_earn_point || 0;
var total_month_point = data.total_point || 0;

But now you can have 1/0 which would be infinity. :)

Other option is to Check for NaN and than set the value to zero.

var performance = (((total_month_earn)/(total_month_point))*100);
var formatted = isNaN(performance) ? "00.00" : performance.toString(2); 

Solution 2:

Fix is as below Replace

performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);

With

try {
  performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);
  performance=isNaN(performance) ? "00.00" : performance;
}
catch(err) {
  performance="00.00";
}

Post a Comment for "Getting Nan If Variable Has Null Value"