Dhairya Shah
Dhairya Shah's Blog

Dhairya Shah's Blog

Style number likes Social media with Javascript

Style number likes Social media with Javascript

Dhairya Shah's photo
Dhairya Shah
Β·Nov 21, 2022Β·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

All the big social media sites format their numbers like 12.3M or 1.2B:

Social Media numbering

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:

not the real code

Just joking, we won't be using this highly complicated code.

let's work smart

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
    const formatter = Intl.NumberFormat('en', {notation: 'compact'})
    
    To format the number, we have to use format() method.
    let n = formatter.format()
    
    For example,
    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!

Β 
Share this