'Chart.js hover over slice get NaN percentage

I have some trouble when trying to show the percentage of a slice when hovering over using chart.js. The part where I hover over as such:

var options = {
    responsive: true,
    // show percentage of slice when hover
    tooltips: {
    callbacks: {
        label: function(tooltipItem, data) {
            var allData = data.datasets[tooltipItem.datasetIndex].data;
            var tooltipLabel = data.labels[tooltipItem.index];
            var tooltipData = allData[tooltipItem.index];
            var total = 0;
            for (var i in allData) {
                total += allData[i];
            }
            var tooltipPercentage = Math.round((tooltipData / total) * 100);
            return tooltipLabel + ': $ ' + tooltipData + ' (' + tooltipPercentage + '%)';
        }
    }
    }
};

I am able to plot out the chart as such:

The values are correct. But when I hover over, why is the percentage returning me NaN?



Solution 1:[1]

Try this:

var options = {
        responsive: true,
        // show percentage of slice when hover
        tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                var allData = data.datasets[tooltipItem.datasetIndex].data;
                var tooltipLabel = data.labels[tooltipItem.index];
                var tooltipData = allData[tooltipItem.index];
                var total = 0;
                for (var i=0; i<allData.length; i++) {
                    total += allData[i];
                }
                var tooltipPercentage = Math.round((tooltipData / total) * 100);
                return tooltipLabel + ': $ ' + tooltipData + ' (' + tooltipPercentage + '%)';
            }
        }
        }
    };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chinmay jain