Abbreviate a localized number in JavaScript for thousands (1k) and millions (1m)

后端 未结 1 983
野性不改
野性不改 2020-12-21 02:34

I am using the following Javascript to display my Instagram follower count on my site.



        
相关标签:
1条回答
  • 2020-12-21 03:12
    function intlFormat(num)
    {
      return new Intl.NumberFormat().format(Math.round(num*10)/10);
    }
    function makeFriendly(num)
    {
      if(num >= 1000000)
        return intlFormat(num/1000000)+'M';
      if(num >= 1000)
        return intlFormat(num/1000)+'k';
      return intlFormat(num);
    }
    

    Yields:

    makeFriendly(1234567)
    "1.2M"
    makeFriendly(123457)
    "123.5k"
    makeFriendly(1237)
    "1.2k"
    makeFriendly(127)
    "127"
    

    Intl is the Javascript standard 'package' for implemented internationalized behaviours. Intl.NumberFormatter is specifically the localized number formatter. So this code actually respects your locally configured thousands and decimal separators.

    0 讨论(0)
提交回复
热议问题