ashwinmram's avatar

How to format Chartisan charts with currency and commas

FYI I use Chartisan with the laravel adapter found here: https://charts.erik.cat/ so the syntax might be a little different... not sure ;)

I was struggling with this today and got it working finally. The solution is different whether you use bar or pie charts.

Here is the solution for bar charts.

this.chart = new Chartisan({
  el: element,
  data: this.data,
  hooks: new ChartisanHooks()
    .beginAtZero()
    .colors()
    .custom(function ({ data, merge }) {
      // data ->   Contains the current chart configuration
      //           data that will be passed to the chart instance.
      // merge ->  Contains a function that can be called to merge
      //           two javascript objects and returns its merge.

      return merge(data, {
        options: {
          tooltips: {
            callbacks: {
              label: function (t) {
                return (
                  "$" + // currency code of choice
                  t.yLabel
                    .toFixed(2) // 2 decimals with trailing 0
                    .toString()
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                );
              },
            },
          },
        },
      });
    }),
});

The pie/donut chart version is a little different:

this.chart = new Chartisan({
  el: element,
  data: this.data,
  hooks: new ChartisanHooks()
    .legend()
    .datasets("doughnut")
    .pieColors()
    .custom(function ({ data, merge }) {
      return merge(data, {
        options: {
          tooltips: {
            callbacks: {
              label: function (tooltipItem, data) {
                var indice = tooltipItem.index;
                return (
                  data.labels[indice] +
                  ": " +
                  "$" + // currency code of choice
                  data.datasets[0].data[indice]
                    .toFixed(2) // 2 decimals with trailing 0
                    .toString()
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                );
              },
            },
          },
        },
      });
    }),
});
0 likes
2 replies
jlcain3's avatar

Hey ashwinmram

Thanks for posting this, was exactly what i needed!

1 like
tmascroft's avatar

I know this is an old thread but thanks a bunch, was dreading having to figure that one out myself!

1 like

Please or to participate in this conversation.