Module:Coins2

From Roat Pkz
Revision as of 09:26, 19 May 2024 by Hefner (talk | contribs)
Jump to navigation Jump to search

Documentation for this module may be created at Module:Coins2/doc

local p = {}

local function amount(a)
    -- convert used globals to locals where possible to improve performance
    local math = math
    local string = string
    local table = table
    local mw = mw
    local expr = mw.ext.ParserFunctions.expr

    -- strip commas from input
    a = string.gsub(a, ',', '')
    
    -- check for decimals/division to determine if output should have forced 2 decimal places
    local has_decimal_or_division = false
    if string.match(a, "[./]") then
        has_decimal_or_division = true
    end
    
    -- for performance reasons, only calculate expr if required
    if tonumber(a) == nil then
        a = tonumber(expr(a)) or 0
    end
    
    -- round to two decimal places
    a = math.floor(a * 100 + 0.5) / 100

    -- format number with commas
    if has_decimal_or_division then
        local b = 0
        a, b = math.modf(a)
        b = math.abs(b)
        -- hack fix for formatNum stripping the sign from -0
        if (a > 999 or a < -999) then
            a = mw.language.getContentLanguage():formatNum(a)
        end
        b = string.sub(string.format("%.2f", b),2)
        return a .. b
    else
        return mw.language.getContentLanguage():formatNum(a)
    end
end

--
-- {{Coins}} access point
--
function p.amount(frame)
    local args = frame:getParent().args
    -- for {{coins|111}}
    local a = args[1] or '0'
    return amount(a)
end

--
-- Module access point
--
function p._amount(a)
    a = tostring(a) or '0'
    return amount(a)
end

return p