Last active
April 4, 2022 05:28
-
-
Save hsingtism/7ba9d82f68ebe7174f3b683980f432f4 to your computer and use it in GitHub Desktop.
A function that convert integers to English words (short 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 numToWord(num) { | |
if (!Number.isSafeInteger(num) || num < 0) return null | |
if (!num) return 'zero ' | |
const ntt = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '] | |
let mstr = '' | |
let nArr = num.toString().padStart(18, '0').match(/.{1,3}/g) | |
for (let i = 5; i > -1; i--) { | |
let wkv = nArr.shift() | |
if (!+wkv) continue | |
if (+wkv[0]) mstr += ntt[+wkv[0]] + 'hundred ' | |
if ((+wkv[0] || !i) && wkv % 100 && num > 100) mstr += 'and ' | |
wkv %= 100 | |
if (wkv > 19) { | |
mstr += ['', 'ten ', 'twenty ', 'thirty ', 'fourty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety '][~~(wkv / 10)] | |
wkv %= 10 | |
} | |
mstr += ntt[wkv] + ['', 'thousand ', 'million ', 'billion ', 'trillion ', 'quadrillion '][i] | |
} | |
return mstr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment