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 |
||
(One intermediate revision by the same user not shown) | |||
Line 11: | Line 11: | ||
end | end | ||
-- | -- If the number is negative, then we need to add a negative sign to the | ||
local formatted = tostring( | -- 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 30: | ||
end | end | ||
end | end | ||
return formatted | return formatted | ||
end | end | ||
return p | return p |
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