13

I want to display numbers using a Metric Prefix with 3 significant digits like so:

1 shows as 1
999 shows as 999
1000 shows as 1K
999000 shows as 999K
1000000 shows as 1M
1500000 shows as 1.5M
1000000000 shows as 1G
etc...

I could write my own javascript function to do this but I was wondering if there is a standard way of formatting numbers like this?

magritte
  • 7,396
  • 10
  • 59
  • 79
  • @Juhana thanks, that's exactly what I was looking for, not sure why I didn't see it - voted to close my question. – magritte Jul 13 '13 at 19:27

1 Answers1

33

You can put the ranges in an array of objects, and just loop through it to format the number:

var ranges = [
  { divider: 1e18 , suffix: 'E' },
  { divider: 1e15 , suffix: 'P' },
  { divider: 1e12 , suffix: 'T' },
  { divider: 1e9 , suffix: 'G' },
  { divider: 1e6 , suffix: 'M' },
  { divider: 1e3 , suffix: 'k' }
];

function formatNumber(n) {
  for (var i = 0; i < ranges.length; i++) {
    if (n >= ranges[i].divider) {
      return (n / ranges[i].divider).toString() + ranges[i].suffix;
    }
  }
  return n.toString();
}

Usage example:

var s = formatNumber(999000);

To also handle negative numbers, you would add this first in the function:

  if (n < 0) {
    return '-' + formatNumber(-n);
  }
aloisdg
  • 22,270
  • 6
  • 85
  • 105
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • That's a neat idea, thanks - I need to tweak it a bit though to get a max of 3 significant figures to show. I changed your toString() to a toFixed() call which almost does it, but 999999 shows as 1000k rather than 1M. – magritte Jul 13 '13 at 19:56
  • @magritte: Well, it rather should, as 999999 is not quite 1000000, so it's 999.999 k. – Guffa Jul 31 '13 at 16:21
  • 1
    Another option for negative numbers is `if (Math.abs(n) >= ranges[i].divider)`. – Maxim Egorushkin Sep 23 '16 at 14:46
  • You mixed 'P' and 'E' (see https://en.wikipedia.org/wiki/Metric_prefix). I updated it. – aloisdg Apr 23 '18 at 14:44