Created
April 14, 2021 02:57
-
-
Save jgdovin/296010764a5a79da551570da0a8dfa1f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const numberWords = [ | |
'', | |
'one', | |
'two', | |
'three', | |
'four', | |
'five', | |
'six', | |
'seven', | |
'eight', | |
'nine', | |
'ten', | |
'eleven', | |
'twelve', | |
'thirteen', | |
'fourteen', | |
'fifteen', | |
'sixteen', | |
'seventeen', | |
'eighteen', | |
'nineteen', | |
'twenty' | |
]; | |
numberWords[30] = 'thirty'; | |
numberWords[40] = 'fourty'; | |
numberWords[50] = 'fifty'; | |
numberWords[60] = 'sixty'; | |
numberWords[70] = 'seventy'; | |
numberWords[80] = 'eighty'; | |
numberWords[90] = 'ninety'; | |
const suffix = { | |
0: '', | |
1: ' thousand ', | |
2: ' million ', | |
3: ' billion ', | |
4: ' trillion ', | |
5: ' quadrillion ', | |
6: ' quintillion ', | |
7: ' sextillion ', | |
8: ' septillion ' | |
} | |
const subNumberToHuman = number => { | |
if (!number) { | |
return ''; | |
} | |
let result = ''; | |
const firstTwoDigits = number%100; | |
if (numberWords[number%100]) { | |
result = `${numberWords[number%100]}`; | |
} else { | |
const firstDigit = number%10; | |
const secondDigit = Math.floor(number%100/10) * 10 | |
result = numberWords[firstDigit]; | |
if (secondDigit) { | |
result = `${numberWords[secondDigit]} ${result}` | |
} | |
} | |
const thirdDigit = Math.floor(number/100); | |
let tmpRes = ''; | |
if (thirdDigit) { | |
tmpRes = `${numberWords[thirdDigit]} hundred`; | |
} | |
result = `${tmpRes}${result}`; | |
return result; | |
}; | |
const numberToHuman = number => { | |
let result = ''; | |
let count = 0; | |
let remainder = number; | |
while (remainder > 0) { | |
const subNumber = subNumberToHuman(remainder % 1000); | |
if (subNumber) { | |
result = `${subNumber}${suffix[count]}${result}`; | |
} | |
remainder = Math.floor(remainder / 1000); | |
count++; | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment