Skip to content

Instantly share code, notes, and snippets.

@iksent
Last active June 3, 2022 09:39
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 iksent/a2b4e9d3d550fb1d4a755ab2c903ab86 to your computer and use it in GitHub Desktop.
Save iksent/a2b4e9d3d550fb1d4a755ab2c903ab86 to your computer and use it in GitHub Desktop.
Number Formatters
export const toFixedN = (
number: number | null | undefined,
fractionDigits = 8,
canBeNull = true,
): string => {
let num = number
// @ts-ignore
num = +num
if (isNaN(num)) {
return '-'
}
if (num === 0) {
return canBeNull ? '0' : '~0'
}
if (num < 1) {
// Cannot use parseFloat for small values due to exponential form
// @ts-ignore
num = num.toFixed(fractionDigits).replace(/\.0+$/, '').replace(/0+$/, '')
} else {
num = parseFloat(num.toFixed(fractionDigits))
}
// @ts-ignore
return +num === 0 ? (canBeNull ? '0' : '~0') : num.toString()
}
const SI_SYMBOL = ['', 'k', 'M', 'B', 'T', 'q', 'Q']
export const abbreviateNumber = (
number: number,
params?: { fixed?: number },
) => {
// if zero, we don't need a suffix
// eslint-disable-next-line eqeqeq
if (number == 0) {
return '0'
}
if (number > -1 && number < 1) {
return number
}
// what tier? (determines SI symbol)
const tier = (Math.log10(Math.abs(number)) / 3) | 0
// get suffix and determine scale
const suffix = SI_SYMBOL[tier]
const scale = Math.pow(10, tier * 3)
// scale the number
const scaled = number / scale
// format number and add suffix
return [
typeof params?.fixed === 'number' ? toFixedN(scaled, params?.fixed || 0) : scaled,
suffix,
].join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment