Last active
October 7, 2019 11:40
-
-
Save jpillora/ab59ef6b7356f5660942e74eb93dae56 to your computer and use it in GitHub Desktop.
Scale
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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