 1  # How can I turn a number into words? Bubby4j 231 9 years ago

Say you have a number, make it 192,540,520

How can you turn this number into this string: one hundred ninety two million five hundred fourty thousand five hundred twenty

1   AxeOfMen 434 9 years ago

This is a really fun exercise that involves recursion. I highly recommend attempting to work through this problem on your own before simply using the solution I present below. Take your time. Experiment with it. Have fun!

With that said, I present my solution here...

local stringVals = {
 = "",
 = "one",
 = "two",
 = "three",
 = "four",
 = "five",
 = "six",
 = "seven",
 = "eight",
 = "nine",
 = "ten",
 = "eleven",
 = "twelve",
 = "thirteen",
 = "fourteen",
 = "fifteen",
 = "sixteen",
 = "seventeen",
 = "eighteen",
 = "nineteen",
 = "twenty",
 = "thirty",
 = "forty",
 = "fifty",
 = "sixty",
 = "seventy",
 = "eighty",
 = "ninety",
 = "hundred",
 = "thousand",
}

local groupNames = {
 = "",
 = " thousand ",
 = " million ",
 = " billion ",
}

local function groupToWord(number)
local result = stringVals[number]
if not result then
result = ""
local hundreds = math.floor(number/100)
if hundreds > 0 then
result = result .. stringVals[hundreds] .. " " .. stringVals .. " "
end
number = number - hundreds * 100
local tens = math.floor(number/10)
number = number - tens * 10
if tens == 1 and number > 0 then
--address funny names eleven thru nineteen
result = result .. stringVals[number + 10]
else
if tens > 0 then
result = result .. stringVals[tens * 10] .. " "
end
if number > 0 then
result = result .. stringVals[number]
end
end
end
return result
end

local function numberToWords(number, groupIndex)
if number then
groupIndex = groupIndex or 1
local numStr = tostring(number)
local endStr = numStr:sub(-3)
local front = numStr:sub(1,-4)
return numberToWords(tonumber(front), groupIndex + 1) .. groupToWord(endStr) .. groupNames[groupIndex]
else
return ""
end
end

for i = 100, 2000, 13 do
print(i, numberToWords(i))
end


select output:

178 one hundred seventy eight

217 two hundred seventeen

334 three hundred thirty four

555 five hundred fifty five

685 six hundred eighty five

867 eight hundred sixty seven

1010 one thousand ten

1491 one thousand four hundred ninety one

1816 one thousand eight hundred sixteen

1998 one thousand nine hundred ninety eight

192540520 one hundred ninety two million five hundred forty thousand five hundred twenty 