Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js 2.0 Formatting Y Axis with Currency and Thousands Separator

I am having problems with formatting my chart axis and I am not able to find an example for the updated version 2.0.

How can I (for example) make 2000000 to €2.000.000?

My fiddle: https://jsfiddle.net/Hiuxing/4sLxyfya/4/

window.onload = function() {
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myBar = new Chart(ctx, {
        type: 'bar',
        data: barChartData,
        options: {
            title: {
                display:true,
                text:"Figure"
            },
            legend: {
                position: "bottom"
            },
            tooltips: {
                mode: 'label',
                bodySpacing: 10,
                cornerRadius: 0,
                titleMarginBottom: 15
            },
            scales: {
                xAxes: [{
                    ticks: {}
                }],
                yAxes: [{
                    ticks: {
                        beginAtZero: true,
                        stepSize: 500000
                    }
                }]
            },
            responsive: true
        }
    });
};
like image 791
Mae Avatar asked Apr 28 '16 15:04

Mae


1 Answers

The Fix

Assign a function into userCallback when creating the config object. This gets called when creating the tick marks. You can find documentation at Chart.js at the bottom of Scales Documentation

Example fiddle with the fix

yAxes: [{
    ticks: {
        beginAtZero: true,
        stepSize: 500000,

        // Return an empty string to draw the tick line but hide the tick label
        // Return `null` or `undefined` to hide the tick line entirely
        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;
        }
    }
}]
like image 109
L Bahr Avatar answered Sep 22 '22 11:09

L Bahr