29

I've tried some several answers here in stackoverflow but to no avail failed to make it work.. I'm really new in Chart.js so please bear with me.

this is what I have tried so far. Add Commas to ChartJS Data Points and this Chart.js number format

here's my code:

thanks in advance.

Chart.defaults.global.legend = {
 enabled: false
};

function load_yearly_sales_per_agent(param_year, transaction_url){
    $(".custom_loader").show();
    $(".custom_graph").hide();
    $.ajax({
        url:transaction_url,
        type:'post',
        data: {year : param_year},
        dataType:'json',
        success:function(result){
              // Bar chart
              var ctx = document.getElementById("mybarChart");
              var mybarChart = new Chart(ctx, {
                responsive: true,
                multiTooltipTemplate: "<%=addCommas(value)%>",
                type: 'bar',
                data: {
                  labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                  datasets: [{
                    label: 'Sales Per Month',
                    backgroundColor: "#26B99A",
                    data: result
                  }]
                },

                options: {
                  scales: {
                    yAxes: [{
                      ticks: {
                        beginAtZero: true
                      }
                    }]
                  }
                }
              });
              $(".custom_loader").hide();
              setTimeout(function(){
                $(".custom_graph").show();
              }, 200);
        }
    });
}

what I want is to add comma on tooltip and Y-axis.....

enter image description here

Community
  • 1
  • 1
Sam Teng Wong
  • 2,379
  • 5
  • 34
  • 56

8 Answers8

29

For your yAxes ticks options, this will add commas at the thousands marks:

ticks: {
    beginAtZero:true,
    userCallback: function(value, index, values) {
        value = value.toString();
        value = value.split(/(?=(?:...)*$)/);
        value = value.join(',');
        return value;
    }
}

Similar function can be added in a tooltip callback.

Full example in this FIDDLE

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
dangre00
  • 450
  • 3
  • 9
  • 1
    doesn't work if there are decimal places - see other answers instead – Lance Jun 13 '18 at 22:10
  • 1
    I adapted the full example with an improved number formatter (though `Number(x).toLocaleString()` might be better) and more modern ES syntax: https://codesandbox.io/s/confident-payne-nrrhr (The old jsfiddle version was rendering weirdly.) – seanf Jun 29 '19 at 09:51
  • how to use this with multiple datasets? – user3613026 Jun 20 '21 at 12:16
25

I see a lot of overly complicated answers for this.

This functionality is already built into javascript with .toLocaleString(), we don't have to reinvent to wheel! This accounts for decimals as well.

yAxes: [
    {
        ticks: {
            beginAtZero: true,
            userCallback: function(value, index, values) {
                return value.toLocaleString();   // this is all we need
            }
        }
    }
]
Phil
  • 3,342
  • 5
  • 28
  • 50
20

the accepted answer would not place commas in the correct place if decimals are being used

45000.00 would display as 45,000,.00

used the following code for chartjs ver 2.3

       options: {
            responsive: true,
            maintainAspectRatio: false,
        tooltips: {
          callbacks: {
                label: function(tooltipItem, data) {
                    var value = data.datasets[0].data[tooltipItem.index];
                    if(parseInt(value) >= 1000){
                               return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                            } else {
                               return '$' + value;
                            }
                }
          } // end callbacks:
        }, //end tooltips                
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        callback: function(value, index, values) {
                            if(parseInt(value) >= 1000){
                               return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                            } else {
                               return '$' + value;
                            }
                       }                            
                    }
                }]
            }
        }
Jay Rizzi
  • 4,196
  • 5
  • 42
  • 71
  • 1
    the tooltip callback works better if you use 'var value = tooltipItem.yLabel;' instead of accessing the data directly - as sometimes the data is .x & .y or mixed – Lance Jun 13 '18 at 22:24
  • 9
    Here is the fix for multiple datasets: `var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];`. (Don't hardcode the dataset index as 0.) – ndbroadbent May 23 '19 at 09:09
11

The accepted answer works fine for charts that have a single dataset per column, such as a bar chart. The hardcoded dataset location causes the solution to fail for multi-dataset charts such as line charts. The solution is to replace the hardcoded dataset index location (data.datasets[0]) with a dynamic index location built into chartjs (data.datasets[tooltipItem.datasetIndex]).

The formatting of the numbers can be best accomplished by formatting the value according to the user's locale settings. This helps ensure that numbers use the correct decorators (thousands separator can be a comma or a period, depending on the user's locale).

options: {
  tooltips: {
    callbacks: {
      label: function (tooltipItem, data) {
        var tooltipValue = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        return parseInt(tooltipValue).toLocaleString();
      }
    }
  }
}
Steven B.
  • 284
  • 4
  • 10
2

I'm just spitballing here but, assuming data is an array, couldn't you just loop through and add commas?

datasets: [{
    label: 'Sales Per Month',
    backgroundColor: "#26B99A",
    data: result.map(function (i) {
       return i.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    })
}]
jjwilly16
  • 410
  • 2
  • 8
  • 15
  • this is my first solution to the problem but happens to be not working..... I happen to solve the problem... I was able to locate the tooltip and I just add a function that add the comma there.... – Sam Teng Wong Aug 06 '16 at 04:20
1

For more currency conversion

ticks: {
    beginAtZero: true,
    callback: function(label, index, labels) {
        return Intl.NumberFormat('hi', { style: 'currency', currency: 'INR', minimumFractionDigits: 2 }  )
        .format(label).replace(/^(\D+)/, '$1 ');
    },
}

// ₹ 1,400.00
Dexter
  • 7,911
  • 4
  • 41
  • 40
0

There is a specific javascript function to convert a long number into a number formatted according to system settings: toLocaleString().

You can specify that the label of each tick (or of a specific tick identified by its number index) must be built by your own function, by adding "callback:" keyword inside tick options:

Before:

        ticks: {
                  max: maxAltitude,
                  min: 0
                }

After:

        ticks: {
                  max: maxAltitude,
                  min: 0, // <--- dont' foget to add this comma if you already have specified ticks options
                    callback:  
                      function(value, index, valuesArray) {
                          // value: currently processed tick label
                          // index of currently processed tick label
                          // valuesArray: array containing all predefined labels
                          return  value.toLocaleString(); 
                      } // Function end
                } // Ticks options end

Without the comments and without unused variables:

        ticks: {
                  max: maxAltitude,
                  min: 0, 
                  callback:  
                      function(value) {
                        return  value.toLocaleString(); 
                      }
                }

Same method can be applied to tooltips.

jumpjack
  • 841
  • 1
  • 11
  • 17
0

(This example show money)

callback: function(value, index, values){
               return value.toLocaleString("en-US",
              {style:"currency", 
                currency:"USD",
                minimumFractionDigits: 0, 
                maximumFractionDigits: 0});
           }
DeltaTango
  • 821
  • 2
  • 9
  • 19