[Chartjs]-Thousand separator in pie chart of charts.js

10πŸ‘

βœ…

In order to do this in chart.js, you need to use the tooltips.callbacks.label callback property. The value returned from this callback is what is used to generate the tooltip text.

Here is your chart configured with a tooltip callback that uses the local string representation for your data value.

var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"],
    datasets: [{
      backgroundColor: ["#00b638","#efaa30","#50c8ea"],
      data: [500000, 75000, 100000]
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Employee Overview',
      fontStyle: 'bold',
      fontSize: 20
    },
    tooltips: {
      callbacks: {
        // this callback is used to create the tooltip label
        label: function(tooltipItem, data) {
          // get the data label and data value to display
          // convert the data value to local string so it uses a comma seperated number
          var dataLabel = data.labels[tooltipItem.index];
          var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();

          // make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
          if (Chart.helpers.isArray(dataLabel)) {
            // show value on first line of multiline label
            // need to clone because we are changing the value
            dataLabel = dataLabel.slice();
            dataLabel[0] += value;
          } else {
            dataLabel += value;
          }

          // return the text to display on the tooltip
          return dataLabel;
        }
      }
    }
  }
});

You can see it in action at this codepen.

Leave a comment