Reduce the localized number in JavaScript for thousands (1k) and millions (1m)

I am using the following Javascript to display my Instagram counter 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 a comma where necessary. I would also like to display a reduced number of followers, e.g. 3.291 , like 3.2k , in another class. Thus, maintaining the total number of followers in one class and reducing it in another. I'm not the best at JavaScript, but I was learning slowly.

I found a similar question ( Is there a way to round numbers in a reader-friendly format (for example, $ 1.1 thousand) ), but they could not implement it in my JavaScript.

Any help is greatly appreciated.

+2
javascript instagram
Sep 01 '14 at 19:27
source share
1 answer
 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); } 

Productivity:

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

Intl is the standard Javascript package for implemented internationalized behaviors. Intl.NumberFormatter is, in particular, a number localizer . Thus, this code really respects your locally configured thousands and decimal separators.

+6
Sep 01 '14 at 19:36
source share
— -



All Articles