Search code examples
typescriptchart.js

How to use Ticks formatter with Typescript in Chart.js?


If I make Chart.js to use locale en-US, I get the scale numbers formatted optimally. enter image description here

If I use tick callback like in the documents:

ticks: {
     callback: function(value) {
        return value.toString();
     }
}

I don't get optimal width for the numbers.

enter image description here

The aforementioned document instructs that it should be possible to combine Chart.js format and custom

Chart.Ticks.formatters.numeric.apply(this, [value, index, ticks]);

This however does not work for typescript, but I get error "Property 'Ticks' does not exist on type 'typeof Chart'."

Another variant I tried is

Chart.registry.scales.get('ticks')?.formatters.numeric.apply(this, [value, index, ticks])

in which ticks seems to exist, but I don't have a way to reach formatters. Exportable functions from helpers has only formatNumber, which requires locale, and I think that would anyway skip all the number width optimization by Chart.js.

The root cause of the problem is that my client wants the only formatting to be decimal point, and any kind of thousand separator should not exist. It will not be possible to use any kind of manual solution to format the number by cutting decimals etc, as the scale can be anything and zooming to anything is possible.

Chart.js: 4.4.2 Typescript: 4.9.4


Solution

  • I got it working with

          afterTickToLabelConversion: (axis) => {
            axis.ticks.forEach((tick) => tick.label = tick.value?.toString());
          },
    

    This function is called multiple times during one draw, first with initial scale (0,1), then a couple of times with different amount of ticks, ending with seven ticks visible in the chart.