Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active Oct 7, 2019
Embed
What would you like to do?
Scale
//scale returns the number scaled to its corresponding SI suffix.
// scale(1234) => "1.2 K"
//MIT License, Copyright jpillora © 2019
function scale(n, d) {
// set default number
if (typeof n !== "number" || isNaN(n)) n = 0;
if (n === 0) return "0";
// set default digit count
if (typeof d !== "number" || isNaN(d)) d = 1;
// find scale index 1000,100000,... becomes 1,2,...
var i = Math.floor(Math.floor(Math.log10(n)) / 3);
var f = Math.pow(10, d);
var s = Math.round(n / Math.pow(10, i * 3) * f) / f;
// concat (no trailing 0s) and choose scale letter
return (
s.toString().replace(/\.0+$/, "") +
" " +
["", "K", "M", "G", "T", "P", "Z"][i]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment