Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    /* 
        Get access token & ID through http://jelled.com/instagram/access-token
        Register your app here @ Instagram http://instagram.com/developer 
        */
    $(function() {
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            cache: true,
            url: "https://api.instagram.com/v1/users/{ID}/?access_token={ACCES_TOKEN}",
            success: function(data) {
                var ig_count = data.data.counts.followed_by.toString();
                ig_count = add_commas(ig_count);
                $(".instagram_count").html(ig_count);
            }
        });

        function add_commas(number) {
            if (number.length > 3) {
                var mod = number.length % 3;
                var output = (mod > 0 ? (number.substring(0, mod)) : '');
                for (i = 0; i < Math.floor(number.length / 3); i++) {
                    if ((mod == 0) && (i == 0)) {
                        output += number.substring(mod + 3 * i, mod + 3 * i + 3);
                    } else {
                        output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
                    }
                }
                return (output);
            } else {
                return number;
            }
        }
    });
</script>
<span class="instagram_count"> </span>

As you can see, there is a function to add comma's where necessary. I'd like to also display the follower count abbreviated, for example, 3,291 followers as 3.2k, in another class. So keeping the full follower count in one class and the abbreviated in another. I am not the greatest at JavaScript but am slowly learning.

I have found a similar question (Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)) but have had no luck implementing it into my JavaScript.

Any help is greatly appreciated.

like image 770
Jack McLaughlin Avatar asked Sep 01 '14 19:09

Jack McLaughlin


1 Answers

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.

like image 185
Niels Keurentjes Avatar answered Nov 14 '22 22:11

Niels Keurentjes