Skip to content

Instantly share code, notes, and snippets.

@adamstallard
Created January 14, 2025 04:52
Show Gist options
  • Select an option

  • Save adamstallard/8254707aed3eb4f314a2214e54927d99 to your computer and use it in GitHub Desktop.

Select an option

Save adamstallard/8254707aed3eb4f314a2214e54927d99 to your computer and use it in GitHub Desktop.
Shorten numbers with precision and suffixes
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