Skip to content

Instantly share code, notes, and snippets.

@fdcore
Created February 18, 2016 02:09
Show Gist options
  • Save fdcore/37178d288994df03a587 to your computer and use it in GitHub Desktop.
Save fdcore/37178d288994df03a587 to your computer and use it in GitHub Desktop.
// from http://stackoverflow.com/questions/18151877/javascript-shorten-large-numbers-force-decimal-places-and-choose-to-represent
function shortenNumber (num, decimalPlaces) {
var str,
suffix = '';
decimalPlaces = decimalPlaces || 0;
num = +num;
var factor = Math.pow(10, decimalPlaces);
//99999 -> 99.9K
if (num < 1000) {
str = num;
} else if (num < 1000000) {
str = Math.floor(num / (1000 / factor)) / factor;
suffix = 'K';
} else if (num < 1000000000) {
str = Math.floor(num / (1000000 / factor)) / factor;
suffix = 'M';
} else if (num < 1000000000000) {
str = Math.floor(num / (1000000000 / factor)) / factor;
suffix = 'B';
} else if (num < 1000000000000000) {
str = Math.floor(num / (1000000000000 / factor)) / factor;
suffix = 'T';
}
return str + suffix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment