Skip to content

Instantly share code, notes, and snippets.

@alarrosa14
Last active August 2, 2018 12:41
Show Gist options
  • Save alarrosa14/abbec47320f7aec582600caccf956abf to your computer and use it in GitHub Desktop.
Save alarrosa14/abbec47320f7aec582600caccf956abf to your computer and use it in GitHub Desktop.
Angular filter to abbreviate large numbers, optionally receiving the number of decimal places as parameter.
// Based in http://stackoverflow.com/a/2686098/4436816
//
// Usage examples:
// {{ 2134124 | abbreviate:2}} -> 2.13M
// {{ 2134124 | abbreviate }} -> 2M
// {{ 1000 | abbreviate }} -> 1K
myApp.filter('abbreviate', function() {
return function(number, decPlaces) {
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10,decPlaces || 0);
// Enumerate number abbreviations
var abbrev = [ 'K', 'M', 'B', 'T' ];
// Go through the array backwards, so we do the largest first
for (var i=abbrev.length-1; i>=0; i--) {
// Convert array index to '1000', '1000000', etc
var size = Math.pow(10,(i+1)*3);
// If the number is bigger or equal do the abbreviation
if(size <= number) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number*decPlaces/size)/decPlaces;
// Handle special case where we round up to the next abbreviation
if((number === 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
// Add the letter for the abbreviation
number += abbrev[i];
// We are done... stop
break;
}
}
return number;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment