问题
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 print number value like, 00.00
.
Is that possible? If yes then how? Thank you.
My code,
function emp_month_perf(){
jQuery.ajax({
url: "<?php echo base_url(); ?>grade_tasks/emp_monthly_performance",
data:'',
type:"GET",
dataType: "json",
success:function(data){
var total_month_earn = data.total_earn_point;
var total_month_point = data.total_point;
var performance;
var per_color;
//var radius = "20px";
//alert(total_point);
performance = (((total_month_earn)/(total_month_point))*100).toFixed(2);
if(performance>80)
{
per_color = "#33CF53";
}
else if(performance>=60 && performance<=80)
{
per_color = "#E0C533";
}
else
{
per_color = "#E12827";
}
//document.getElementById("monthperformance").style.borderRadius = radius;
document.getElementById("monthperformance").style.backgroundColor = per_color;
$('#monthperformance').html(performance);
},
error:function (){}
});
}
setInterval(emp_month_perf, 300000);
回答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);
回答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";
}
来源:https://stackoverflow.com/questions/34613774/getting-nan-if-variable-has-null-value