Skip to content

Instantly share code, notes, and snippets.

@thewarpaint
Created August 25, 2014 04:30
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save thewarpaint/889690aeb21a8dfd7aba to your computer and use it in GitHub Desktop.
Save thewarpaint/889690aeb21a8dfd7aba to your computer and use it in GitHub Desktop.
Angular filter to convert numbers to thousand suffixes (1234 > 1.2k)
// Based on http://stackoverflow.com/questions/1571374/converting-values-to-unit-prefixes-in-jsp-page.
// The inner filter function can be used standalone.
angular.module('Utils')
.filter('thousandSuffix', function () {
return function (input, decimals) {
var exp, rounded,
suffixes = ['k', 'M', 'G', 'T', 'P', 'E'];
if(window.isNaN(input)) {
return null;
}
if(input < 1000) {
return input;
}
exp = Math.floor(Math.log(input) / Math.log(1000));
return (input / Math.pow(1000, exp)).toFixed(decimals) + suffixes[exp - 1];
};
});
@sutkovoy
Copy link

sutkovoy commented Sep 9, 2015

Thx man!

@gautam-bst
Copy link

Thanks a lot buddy. But there is only one problem with it. It's rounding up the numbers, for example, 2k for 1800. Whereas, the correct answer should be 1.8k

@sandeeptharayilGit
Copy link

thnx

@eventuallyc0nsistent
Copy link

eventuallyc0nsistent commented Jun 7, 2016

Thanks. I forked it for python2. If anyone wants it.

@samura
Copy link

samura commented Oct 20, 2016

Thanks! You can remove the rounded var, guess it served some purpose in the past.

@zinchenko
Copy link

Thanks!
Worth mentioning, to have 1.8k instead of 1k you have to pass in the 'decimals' parameter as well, like this:
{{ 1800 | thousandSuffix:1}}

@ptldhaval
Copy link

@ajayreddy56
Copy link

ajayreddy56 commented Jul 24, 2017

One problem with this like 1060 round up 1.1k .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment