Module:NumberFormatter

From Idle Clans wiki
Revision as of 11:05, 24 May 2024 by Uraxys (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local p = {}

---Formats a number by adding thousand separators.
---Example: 20000 -> 20,000
function p.formatNumber(frame)
    local num = tonumber(frame.args[1])

    -- Make sure we're working with a number.
    if not num then
        return "Error: '" .. frame.args[1] .. "' is not a number."
    end

    -- If the number is negative, then we need to add a negative sign to the
    -- formatted number.
    if num < 0 then
        return "-" .. addCommas(-num)
    end

    -- If the number is positive, then we can just format it.
   return addCommas(num)
end

---Adds thousand separators to a number.
function addCommas(number)
    local formatted = tostring(number)
    while true do
        formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
        if k == 0 then
            break
        end
    end
    return formatted
end

return p