All the big social media sites format their numbers like 12.3M or 1.2B:
To format the numbers from 19223324 to 19M, we don't need to use any third-party API, or npm package, we just need to write the following:
Just joking, we won't be using this highly complicated code.
Using Internationalization API
The Intl
object is the namespace for the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and the date and time formatting.
- First, let's declare a NumberFormat API
To format the number, we have to useconst formatter = Intl.NumberFormat('en', {notation: 'compact'})
format()
method.
For example,let n = formatter.format()
n = formatter.format(144234234) // 144M n = formatter.format(12431) // 12K
Complete code:
const formatter = Intl.NumberFormat('en', {notation: 'compact'})
let n = formatter.format(12431)
console.log(n)
So now you can format the number like
Thanks for reading
Follow me on Twitter
Thanks for reading!