Getting NaN if variable has null value

爱⌒轻易说出口 提交于 2019-12-24 15:42:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!