I'll show you how to break this into a helper that converts a -digit group, plus a main loop that attaches scale words.
belowTwenty = ["", "One", "Two", ..., "Nineteen"]
tens = ["", "", "Twenty", "Thirty", ..., "Ninety"]
scales = ["", "Thousand", "Million", "Billion"]
function threeDigitToWords(num):
if num == 0:
return ""
result = ""
if num >= 100:
result += belowTwenty[num / 100] + " Hundred "
num = num % 100
if num >= 20:
result += tens[num / 10] + " "
num = num % 10
if num > 0:
result += belowTwenty[num] + " "
return result
function numberToWords(num):
if num == 0:
return "Zero"
result = ""
scaleIndex = 0
while num > 0:
group = num % 1000
if group != 0:
result = threeDigitToWords(group) + scales[scaleIndex] + " " + result
num = num / 1000
scaleIndex += 1
return result.trim()