0

I'm using chartjs-plugin-datalabels to permanently display the datalabels above each chart dataset. I used the following code in each chart script to display the currency amount in US Dollars:

plugins: {
    datalabels: {
        formatter: function(value, context) {
            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
    }
}

which then outputs to: $#,###,###

To save space, how can I rewrite this code to display the above amount in an abbreviated fashion like this: $#.#m. The first comma becomes a decimal point and the remaining integers are rounded.

So, billions would have a B, millions would have a M, and thousands would have a K, etc...

Examples:

$10,500,000,000 --> $10.5b

$1,500,000,000 --> $1.5b

$10,500,00 --> $10.5m

$1,500,000 --> $1.5m

$10,500 --> $10.5k

$1,500 --> $1.5k

A breakdown of the .replace() portion would be appreciated, as well.

apexturtle
  • 57
  • 1
  • 9
  • If you're commited to a one-line regular expression I think it can be done but best just to write a simple function: convert the string to a number and divide by 1000 until it's too small and find the unit (k, m, b) – Halcyon Jun 27 '18 at 22:44
  • I would like to keep it to a one-line expression if I can – apexturtle Jun 27 '18 at 22:53
  • @Halcyon do you have an example of a simple function I could use as stated in your first comment? I can edit javascript pretty well but not much for writing from scratch. – apexturtle Jun 27 '18 at 23:42

1 Answers1

0

Found my answer here:

https://stackoverflow.com/a/14994860/7811137

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return num;
}
apexturtle
  • 57
  • 1
  • 9