Module:Addcommas

From the RuneScape Wiki, the wiki for all things RuneScape
Jump to navigation Jump to search
Module documentation
This documentation is transcluded from Module:Addcommas/doc. [edit] [history] [purge]
Module:Addcommas requires Module:LibraryUtil.
Module:Addcommas is required by .

This module is a helper module to be used by other modules; it may not designed to be invoked directly. See RuneScape:Lua/Helper modules for a full list and more information. For a full list of modules using this helper click here

FunctionTypeUseExample
_add( num )number/stringReturns a string with num formatted with commas. Also works on ranges of numbers; e.g. '10000-100000' -> '10,000-100,000'
_strip( num )stringReturns a string with all commas removed from num.

-- <nowiki>
--
-- Implements {{Addcommas}}
--
local libraryUtil = require('libraryUtil')
local p = {}

--
-- main function
-- keep public so it can be used in other modules
--
function p._add(arg)
	libraryUtil.checkTypeMulti('Module:Addcommas._add', 1, arg, {'number', 'string'})
    local lang = mw.language.getContentLanguage()
    
    if type(arg) == 'number' then
    	return lang:formatNum(arg)
    else
	    local z = tostring(arg)
	    
	    -- strip any existing commas
	    z = z:gsub(',', '')
	    
	    local y = mw.text.split(z, '[%-–]')
	    local x
	
	    -- handle ranges as separate numbers
	    -- required by [[Module:Exchange]] (p._table)
	    if y[1] ~= '' and y[2] then
	        y[1] = tonumber(y[1])
	        y[2] = tonumber(y[2])
	        x = lang:formatNum(y[1]) .. '–' .. lang:formatNum(y[2])
	    else
	        x = lang:formatNum(tonumber(z))
	    end
	
	    return x
	end
end

--
-- strips any existing commas in the input
--
function p._strip(str)
	libraryUtil.checkType('Module:Addcommas._strip', 1, str, 'string')
    return str:gsub(',', '')
end

function p.commas (frame)
    local str = frame:getParent().args[1]
    return p._add(str)
end

return p
-- </nowiki>