Chartjs-How to display currency in Chart js

1๐Ÿ‘

โœ…

You can use the tooltipTemplate option to format the tooltip content and scaleLabel to format the scale value when creating the chart (or set it at a global level) to format it the way you like

...
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
scaleLabel: "<%=value%>",
...

If your formatting is more complicated, you can even use a function, like so

var myChart = new Chart(ctx).Line(data, {
    scaleLabel: function (valueObject) {
        return '$' + valueObject.value.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    tooltipTemplate: function (valueObject) {
        return valueObject.label + ': $' + valueObject.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
});

The formatting bit is from How to print a number with commas as thousands separators in JavaScript


Fiddle โ€“ http://jsfiddle.net/v8w6f0bx/

0๐Ÿ‘

You can also set these options when calling new Chart().

  • options.scales.yAxes.ticks

  • options.tooltips.callbacks.label

This way:

new Chart(document.getElementById("mybarChart"), {
        type: "bar",
        data: data,
        options: {
            scales: {
                yAxes: [{
                        ticks: {
                            beginAtZero: !0,
                            userCallback: function (value, index, values) {
                                // Convert the number to a string and splite the string every 3 charaters from the end
                                value = value.toString();
                                value = value.split(/(?=(?:...)*$)/);

// Convert the array to a string and format the output value = value.join('.'); return ' $ ' + value; } } }] }, tooltips: { mode: 'label', label: 'mylabel', callbacks: { label: function (tooltipItem, data) { var value = Number(data.datasets[0].data[tooltipItem.index]).toFixed(2); return ' $ ' + value; }, }, } } });

`

Leave a comment