Module:NumberFormatter: Difference between revisions
From Idle Clans wiki
No edit summary |
No edit summary |
||
Line 9: | Line 9: | ||
if not num then | if not num then | ||
return "Error: '" .. frame.args[1] .. "' is not a number." | return "Error: '" .. frame.args[1] .. "' is not a number." | ||
end | end | ||
Latest revision as of 11:05, 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 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