[Chartjs]-Dollar sign on y-axis with ChartJS

8👍

The problem here is that chart.js won’t round a string, as it is not supposed to do that for you.

When you append a string to a number, JavaScript will convert it for you and you have no control over the precision.

You can use toFixed to solve your problem:

// Define wherever decimals:
const decimals = 3;
// ...
var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value.toFixed(decimals);
                    }
                }
            }]
        }
    }
});

2👍

The syntax for Chart JS 3+ has changed from the current accepted answer. The new format is as follows –

options: {
    scales: {
        y: {
            ticks: {
                // Include a dollar sign in the ticks
                callback: function(value, index, ticks) {
                    return '$' + value;
                }
            }
        }
    }
}

https://www.chartjs.org/docs/latest/axes/labelling.html

0👍

Try using the Numeral JavaScript library (npm install numeral):

import * as numeral from 'numeral'; //npm i numeral


ticks: {
    callback: (value: any) => {
      return numeral(value).format('$0,0.[00]')
    }
}

That should do the trick!

Leave a comment