WiseJ ChartJS extension - formatting Y-axis values

Answered
0
0

I’ve got a simple chart, with data { DateTime X; float Y }.

I’d like the Y axis labels to be formatted as currency and the X-axis labels to be formatted as Dates.  The X-axis works by using:

myChart.Options.Scales.xAxes[0].Time.DisplayFormats = new { day = "YYYY-MM-DD" };

This must be done in code-behind: the DisplayFormats property is not editable in the Designer.

but I’ve been unable to find the secret recipe for the Y axis.  If I was using ChartJS directly from Javascript, apparently I’d use something like this:

scales: {
  y: {
    ticks: {
      callback: (label) => label.toLocaleString("en-US", { style: "currency", currency: "USD" }),
    },
  },
},

How can I get the same result with the WiseJ ChartJS extension?  Simply pre-formatting the values (so they’re strings) is not the solution….

 

  • Carl Daniel
    This is such a basic thing – charts with currency on the Y axis are not exactly rare! I’m amazed that ChartJS doesn’t have a simple built-in solution for doing this but instead relies on a caller-supplied hook to do basic formatting for numbers (while providing flexible and thorough support for formatting dates).
  • You must to post comments
Best Answer
0
0

The JavaScript you need is:
config.options.scales.yAxes[0].ticks.callback = (label) => `$ ${label}`;

or

config.options.scales.yAxes[0].ticks.callback = (label) => label.toLocaleString("en-US", { style: "currency", currency: "USD" });

You need to run it in the InitScript of the ChartJS widget (so it runs when the chart is set up). In order to do that, you’ll need to create a class derived from ChartJS that uses a custom InitScript. In this sample, that class is called MyChartJS.

See code sample.

  • Carl Daniel
    Thanks – works perfectly!
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.