Module:NumberFormatter: Difference between revisions

From Idle Clans wiki
(Created page with "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 -- Format the number. local formatted = tostring(num) while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if k...")
 
No edit summary
Line 11: Line 11:
     end
     end


     -- Format the number.
     -- If the number is more than -1000 and less than 1000, then we don't need
     local formatted = tostring(num)
    -- to format it.
    if num > -1000 and num < 1000 then
        return num
    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
     while true do
         formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
         formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
Line 19: Line 36:
         end
         end
     end
     end
    -- Return the formatted number.
     return formatted
     return formatted
end
end


return p
return p

Revision as of 11:04, 24 May 2024

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 more than -1000 and less than 1000, then we don't need
    -- to format it.
    if num > -1000 and num < 1000 then
        return num
    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