9

Possible Duplicate:
Is there a way round numbers into a friendly format? (e.g. $1.1k)
How to format numbers similar to Stack Overflow reputation format

I have long numbers in JS and I'd like to make them appear in a shorter, and more eaisier to understand way..

So:

1,000,000 = 1M

1,200,000 = 1.2M

1,450 = 1.45K and so on...

Any ideas how I could do this in JS or JQuery?

Community
  • 1
  • 1

1 Answers1

25

Just for fun, check out Code Golf: Friendly Number Abbreviator

The shortest JS answer:

function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}

p.s. this is probably not the fastest or best solution.

Duplicate: Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)

Community
  • 1
  • 1
David Murdoch
  • 87,823
  • 39
  • 148
  • 191
  • 1
    so I'm guessing `n` is the number, but what is `d` for? thanks –  Feb 18 '12 at 23:51
  • 6
    `d` is the number of decimal places for abbreviation. Note: the code-golf solution leaks `x` and `p` into the global scope...not a good thing. – David Murdoch Feb 19 '12 at 00:24
  • 1
    but i need to use this dynamically and i only have the number to play with. Any way I could get away without inputting the decimal places? –  Feb 19 '12 at 02:37
  • 1
    `d` is the number of decimal place to *display in the abbreviation*, not the input number. If you want to display 1.2k for `1200` you would call the function like this: `m(1200,1)` – David Murdoch Feb 19 '12 at 04:40
  • 1
    I think this is for formatting drive space, no? G = gig's instead of B = billions? Whats P and E? – CpILL Feb 23 '13 at 05:32
  • 1
    G is for billion, P is for quadrillion, and E is for quintillion. Check out this wikipedia article on metric prefixes (http://en.wikipedia.org/wiki/Metric_prefix) for the reasons why things are this way. – David Murdoch Feb 24 '13 at 03:34
  • Why for this ` console.log(m(120000,4));` the output is 0.12M instead of 120k ? – Ezequiel De Simone Feb 13 '19 at 17:11
  • JS has in-build function for this see [here](https://stackoverflow.com/a/66940065/14112947) – bogdanoff Apr 04 '21 at 10:09