Last active
February 9, 2022 06:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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