Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active October 7, 2019 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpillora/ab59ef6b7356f5660942e74eb93dae56 to your computer and use it in GitHub Desktop.
Save jpillora/ab59ef6b7356f5660942e74eb93dae56 to your computer and use it in GitHub Desktop.
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