Encountering NaN when a variable is assigned a null value

Currently, I am using AJAX and JSON to retrieve records. If the variable contains a value, it displays as expected. However, if the variable "performance" is null, it shows NaN. Instead of NaN, I would like to display a number value such as 00.00.

Is it possible to achieve this? If so, how can it be done? Thank you.

This is 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;
                    
                    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.backgroundColor = per_color;
                    $('#monthperformance').html(performance || '00.00');
                },
                error:function (){}
                });
                }
               setInterval(emp_month_perf, 300000);

Answer №1

To make the number zero, use an OR operator.

let total_month_earning = data.total_earning_points || 0;
let total_month_score = data.total_score || 0;

Be cautious with division by zero resulting in infinity! :)

Alternatively, consider checking for NaN and then setting the value to zero.

let performance_ratio = (((total_month_earning)/(total_month_score))*100);
let formatted_performance = isNaN(performance_ratio) ? "00.00" : performance_ratio.toString(2); 

Answer №2

To correct the issue, make the following adjustment:

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

Replace it with:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on showcasing real-time data with Angular's service feature

home.component.ts <h1>{{ (reportsToday$ | async)}}</h1> <div echarts [options]="alertsDaily$ | async"> <div echarts [options]="alertsToday$ | async"> <div [onDisplay]="alertsDaily$ | async"> report.component.ts constructor( ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Steps to cancel an AJAX call in C# .NET:

In the ajax.cs class, I am calling methods from the javascript side. To register this on the default.aspx page load, I did the following: Ajax.Utility.RegisterTypeForAjax(typeof(ajax)); Occasionally, some methods take a long time to execute. In such case ...

Utilizing AngularJS to upload numerous independent attachments to CouchDB

My goal is to upload multiple files to a couchdb document using angularjs. Despite my efforts with an angular.forEach loop, I am facing issues as the asynchronous $http calls do not wait for the previous loop to finish before moving on to the next one. Her ...

Tips for linking JSON data with a variable in an AngularJS controller

Json Data { "TotalRecordCount": 50, "Results": [ { "TestId": 5002, "TestName": "Test 01/05/2016" } ] } Service Example function fetchTestData() { var deferred = $q.defer(); $http.get(TestAppConfig.TestApiRo ...

What steps should I take to properly set up the database.json file in order for my app's API to establish a connection with the database

Struggling with getting this cloned app up and running, I feel like I'm hitting a wall. Sharing the database.json file that's giving me trouble: { "development": { "username": "root", "password": ...

Enhance the State in a React application Chrome Extension

I've developed a chrome extension with create-react-app to analyze the HTML of the current page and extract the number of relevant icons from that HTML. While I can successfully build and launch the extension in Chrome, I encounter an issue when atte ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

Is it possible to eliminate repeated words within an HTML element's text content?

I am struggling with replacing words in HTML. <p id ="demo">Hello, Hello how are you! </p> I want the final result to be: Hello, how are you! My solution involves filtering out duplicates and joining them back together. var s ...

serving JSON and HTML responses using a PHP script

After searching through the questions here, I couldn't find a solution. As someone new to PHP and jQuery, I appreciate your patience as I explain my issue. My goal is to send an ajax request using jQuery to a script that runs a mysql query on data fr ...

Not all databases are retrieved in the search query

When I make an API call to get all the Database entries, I am encountering an issue. The response I receive only includes a few databases instead of all of them. async function checkDatabases(item){ if(item.object == 'database') ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

Building a Java application that utilizes a JSON object

I am trying to convert a JSON format into Java code using JSONObject and JSONArray, but I am facing difficulties in getting the output in the desired format. The JSON format is provided below: var transaction_Data = [ { "key": "PASSED", "valu ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Can you explain the variance between using $(“selector”) and $(“selector”).toArray() in jQuery?

While looking through the documentation for toArray(), I decided to test it out in the console. But as I compared calling toArray() on a selector versus calling the selector itself, I couldn't spot any differences. Both methods gave me the same outco ...

Updating backgroundPosition for dual background images within an HTML element using Javascript

Issue at Hand: I am currently facing a challenge with two background images positioned on the body tag; one floating left and the other right. The image on the left has a padding of 50px on the left side, while the image on the right has a padding of 50px ...

JavaScript technique for dynamically clicking an 'a href link'

Similar Question: Is it possible to simulate a click event on a link or element using JavaScript? How can I programmatically click an anchor (href) link using JavaScript? I have the following code to trigger JavaScript functionality when the link is cl ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

Is it possible to use ng-src to point to a file stored locally?

I am currently experimenting with using ng-src to load images from a local folder, but I keep encountering 404 errors. Can ng-src actually reference a local folder, or do you always have to use a hardcoded path like http://example.com/imgs/{{work.img}}.jpg ...