Created
January 14, 2025 04:52
-
-
Save adamstallard/8254707aed3eb4f314a2214e54927d99 to your computer and use it in GitHub Desktop.
Shorten numbers with precision and suffixes
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
| function shortNum(n, p=3, e=p-3) { | |
| if (n === 0) return '0'; | |
| let ans; | |
| const absn = Math.abs(n); | |
| if (absn < Math.pow(10, -1 * p) || absn >= 10 ** 18 ){ | |
| ans = Number.parseFloat(n).toExponential(Math.max(e, 0)); | |
| } | |
| else if (absn < 1){ | |
| ans = Number.parseFloat(n).toFixed(p); | |
| } | |
| else { | |
| const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; | |
| const index = Math.floor(Math.log10(absn) / 3); | |
| const scaled = n / 10 ** (index * 3); | |
| ans = scaled.toPrecision(p) + suffixes[index]; | |
| } | |
| ans = ans.replace(/\.0+(\D|$)/,'$1'); | |
| return ans.replace(/(\.\d*?)0+(\D|$)/,'$1$2'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment