0

I'm stack with this and needed help, I am using a chart js to create a graph but I want the labels AS WELL AS the data to be diplayed in currency format.

e.g. 120000 should be $120,000 in the Label (Y axis) and the actual data when you hover to be display in currency format as well.

myGraph

thank you !

Francis Saul
  • 728
  • 2
  • 16
  • 37

2 Answers2

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/

Community
  • 1
  • 1
potatopeelings
  • 40,709
  • 7
  • 95
  • 119
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;
                }, },
        }
    }
});

`

Pedro Alvares
  • 479
  • 5
  • 9