Forked from cho45/format-number-with-si-prefix.js
Last active
September 13, 2022 06:33
-
-
Save worc/2bfd196cd5caefd141a2612731c12453 to your computer and use it in GitHub Desktop.
but with mu for micro
This file contains 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
function formatN (n) { | |
const unitList = ['y', 'z', 'a', 'f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; | |
const zeroIndex = 8; | |
const nn = n.toExponential(2).split(/e/); | |
let u = Math.floor(+nn[1] / 3) + zeroIndex; | |
if (u > unitList.length - 1) { | |
u = unitList.length - 1; | |
} else | |
if (u < 0) { | |
u = 0; | |
} | |
return nn[0] * Math.pow(10, +nn[1] - (u - zeroIndex) * 3) + unitList[u]; | |
} | |
const array = [1e30, 1e9, 1e8, 1e7, 1e6, 2345, 100, 10, 1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 256e-9, 2.55e-12, 1e-13, -1e3, 1e-30]; | |
for (let i = 0, len = array.length; i < len; i++) { | |
const n = array[i]; | |
const formatted = formatN(n); | |
console.log(n, formatted); | |
} |
This file contains 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
1e+30 1000000Y | |
1000000000 1G | |
100000000 100M | |
10000000 10M | |
1000000 1M | |
2345 2.35k | |
100 100 | |
10 10 | |
1 1 | |
0.01 10m | |
0.001 1m | |
0.0001 100μ | |
0.00001 10μ | |
0.000001 1μ | |
2.56e-7 256n | |
2.55e-12 2.55p | |
1e-13 100f | |
-1000 -1k | |
1e-30 0.000001y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment