Number Words Conversion

Share your scripts and packages with other Mudlet users.
Post Reply
Jor'Mox
Posts: 1091
Joined: Wed Apr 03, 2013 2:19 am

Number Words Conversion

Post by Jor'Mox » Mon Aug 20, 2018 12:43 pm

Someone was asking on the Discord how to convert numbers written out with words (i.e. one hundred twenty seven) to their numerical equivalents in Mudlet, so I put together a simple script to do that for numbers up to, but not including, one trillion, but this can easily be extended by adding the appropriate entries in the factors table. As another key limitation, this only covers whole numbers, no decimals.
Code: [show] | [select all] lua
local numbers = {zero = 0, one = 1, two = 2, three = 3, four = 4, five = 5, six = 6,
    seven = 7, eight = 8, nine = 9, ten = 10, eleven = 11, twelve = 12, thirteen = 13,
    fourteen = 14, fifteen = 15, sixteen = 16, seventeen = 17, eighteen = 18,
    nineteen = 19, twenty = 20, thirty = 30, forty = 40, fifty = 50, sixty = 60,
    seventy = 70, eighty = 80, ninety = 90}
local factors = {hundred = 100, thousand = 1000, million = 10^6, billion = 10^9}
    
function convert_number_words(num)
    local words = {}
    for w in string.gmatch(num,"%a+") do
        if numbers[w] then
            table.insert(words,numbers[w])
        elseif factors[w] then
            local len = #words
            local sum = 0
            for k = len, 1, -1 do
                if sum + words[k] < factors[w] then
                    sum = sum + words[k]
                    words[k] = nil
                else
                    break
                end
            end
            table.insert(words,sum*factors[w])
        end
    end
    local total = 0
    for k,v in ipairs(words) do
        total = total + v
    end
    return(total)
end

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 1 guest