Skip to content

Instantly share code, notes, and snippets.

@nicholasxjy
Created March 7, 2019 02:43
Show Gist options
  • Save nicholasxjy/3a2a29f1c0961d86dc4c6b00650b24ae to your computer and use it in GitHub Desktop.
Save nicholasxjy/3a2a29f1c0961d86dc4c6b00650b24ae to your computer and use it in GitHub Desktop.
truncate number with k M G (3001 -> 3k)
function truncateNumber(num, digits = 0) {
const si = [
{ value: 1, symbol: '' },
{ value: 1e3, symbol: 'k' },
{ value: 1e6, symbol: 'M' },
{ value: 1e9, symbol: 'G' },
{ value: 1e12, symbol: 'T' },
{ value: 1e15, symbol: 'P' },
{ value: 1e18, symbol: 'E' }
]
let rx = /\.0+$|(\.[0-9]*[1-9])0+$/
let i
for (i = si.length - 1; i > 0; i--) {
if (num >= si[i].value) {
break
}
}
return (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment