[Chartjs]-Format Chart.JS Data Element To Be Currency

9👍

This can be achieved using the following tool-tips label callback function …

tooltips: {
   callbacks: {
      label: function(t, d) {
         var xLabel = d.datasets[t.datasetIndex].label;
         var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
         return xLabel + ': ' + yLabel;
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var labelsarr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
var values = ["AAAA", 100, 10000, 2310, 24420, 30, 50000, 400000, 70000, 700, 823200, 923200, 1111];

var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: labelsarr,
      datasets: [{
         label: 'Amount',
         data: values,
         backgroundColor: 'rgba(0, 119, 204, 0.8)',
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(t, d) {
               var xLabel = d.datasets[t.datasetIndex].label;
               var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
               return xLabel + ': ' + yLabel;
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               callback: function(value, index, values) {
                  if (parseInt(value) >= 1000) {
                     return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                  } else {
                     return '$' + value;
                  }
               }
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Leave a comment