-1

I'm trying to add commas for the data in chartJS. I've tried some code like what is in this thread: Chart.js number format. But they use tooltip here; my setup is not using tooltips.

Please see my code below.

options: {
        events: false,
        showTooltips: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    min: 0,
                    userCallback: function(value, index, values){
                        value = value.toString();
                        value = value.split(/(?=(?:...)*$)/);
                        value = value.join(',');
                        return value;
                    }
                }
            }]
        },
        legend: {
            display: displayLegend
        },
        animation: {
            duration: 0,
            onComplete: function(){
                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';
                ctx.fillStyle = '#0b7707';

                this.data.datasets.forEach(function(dataset){
                    console.log(dataset);
                    for(var i = 0; i < dataset.data.length; i++){
                        for(var key in dataset._meta){
                            var model = dataset._meta[key].data[i]._model;
                            ctx.fillText(dataset.data[i], model.x, model.y - 13);
                        }
                    }
                });
            }
        }
    }
}

enter image description here

Blues Clues
  • 1,694
  • 3
  • 31
  • 72

1 Answers1

1

You can use toLocaleString to convert your bar label, which is a number, to a comma-separated string.

Modify onComplete function under your animation options to this.

onComplete: function(){
  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';
  ctx.fillStyle = '#0b7707';

  this.data.datasets.forEach(function(dataset){
      for(var i = 0; i < dataset.data.length; i++){
          for(var key in dataset._meta){
              var model = dataset._meta[key].data[i]._model;
              // convert number to comma-separated format
              ctx.fillText(dataset.data[i].toLocaleString(), model.x, model.y - 13);
          }
      }
  });
}

See working example.

Ana Liza Pandac
  • 4,795
  • 2
  • 24
  • 36