How to add comma in this chart js

1.5k views Asked by At

I am using Chart.js and here what I want to happen. My Sample Graph

I need to attach comma on those values to indicate thousand. Ex: 1,000

animation: {
    duration: 500,
    easing: "easeOutQuart",
    onComplete: function (label) {
        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        this.data.datasets.filter(dataset => !dataset._meta[Object.keys(dataset._meta)[0]].hidden).forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,                 
                    scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
                                    ctx.fillStyle = '#000';
                var y_pos = model.y - 5;
                // Make sure data value does not get overflown and hidden
                // when the bar's value is too close to max value of scale
                // Note: The y value is reverse, it counts from top down
                if ((scale_max - model.y) / scale_max >= 0.70)
                   y_pos = model.y + 20; 
                ctx.fillText(dataset.data[i], model.x, y_pos);

            }
        });   

    }
}

This is the code to display those values and I believe the code that will attach those commas should be inside this chunk of code.

I just go this code from this forum. So I am not really sure what's happening. How to display Values above bars

2

There are 2 answers

0
Naren Murali On BEST ANSWER

Use this function.

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Found in the SO answer below.

SO Answer

Demo:

JSFiddle Demo

0
Sandip Solanki On

you can use toLocaleString() for this type issue :

use this link toLocateString for read more