Module:Number to word

From para.wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Number to word/doc

local p = {}

local PREFIXES = {
	"m", "b", "tr", "quadr", "quint", "sext",
	"sept", "oct", "non", "dec", "undec",
	"dodec", "tredec", "quadec", "quindec",
	"sexidec", "septidec", "octidec", "nonidec"
}

local TENS = {
	"twenty", "thirty", "forty", "fifty",
	"sixty", "seventy", "eighty", "ninety"
}

local SPECIAL = {
	"one", "two", "three", "four", "five",
	"six", "seven", "eight", "nine", "ten",
	"eleven", "twelve", "thirteen", "fourteen",
	"fifteen", "sixteen", "seventeen",
	"eighteen", "nineteen"
}

function p.exec(frame)
	if frame == mw.getCurrentFrame() then
        args = frame:getParent().args
    else
        args = frame
    end
    
    local value = tonumber(args[1])
    if value == nil then
    	return args[1]
    end
    
    if value == 0 then
    	return "zero"
    end
    
    local words = {}
    local place = 0
    
    while value > 0 do
    	local word = ''
    	local hundo = value%100
    	
    	if hundo < 20 then
    		word = SPECIAL[hundo]
    	else
    		word = TENS[math.floor(hundo/10) - 1]
    		if hundo%10 ~= 0 then
    			word = word .. '-' .. SPECIAL[hundo%10]
    		end
    	end
    	
    	local prefix = ''
    	if value >= 100 then
    		prefix = SPECIAL[math.floor((value/100)%10)] .. ' hundred '
    	end
    	
    	if place == 0 then
    		table.insert(words, 1, prefix .. word)
    	elseif place == 1 then
    		table.insert(words, 1, prefix .. word .. ' thousand')
    	else
    		table.insert(
    			words, 1, word .. ' ' .. PREFIXES[place - 1] .. 'illion'
    		)
    	end
    	
    	place = place + 1
    	value = math.floor(value/1000)
    end
    
    return table.concat(words, ' ')
end

return p