Skip to content

Instantly share code, notes, and snippets.

@xairoo
Last active February 9, 2022 06:37
Show Gist options
  • Save xairoo/07387472290fe591aa4118281a761bc3 to your computer and use it in GitHub Desktop.
Save xairoo/07387472290fe591aa4118281a761bc3 to your computer and use it in GitHub Desktop.
Reduce a number and add thousand, million, billion, trillion, quadrillion, ... return an object with the number and the scale
function numberToScale(number) {
const scales = [
'',
'thousand',
'million',
'billion',
'trillion',
'quadrillion',
'quintillion',
'sextillion',
'septillion',
'octillion',
'nonillion',
];
if (number === 0) {
return { number: 0, scale: '' };
}
const i = parseInt(Math.floor(Math.log(number) / Math.log(1000)), 10);
if (i === 0) {
return { number: parseFloat(number), scale: scales[i] };
}
return {
number: parseFloat((number / 1000 ** i).toFixed(1)),
scale: scales[i],
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment