Skip to content

Instantly share code, notes, and snippets.

@wiedymi
Last active December 12, 2019 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wiedymi/486449cd1ac8c2d9fab42637930d089f to your computer and use it in GitHub Desktop.
Save wiedymi/486449cd1ac8c2d9fab42637930d089f to your computer and use it in GitHub Desktop.
nFormatter.ts
export function nFormatter(num, digits = 4): string {
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' },
]
const 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