Search code examples
javascriptformattingchart.jscurrency

How to rewrite JavaScript currency formatting to abbreviate dollar amount


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.


Solution

  • 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;
    }