Anonymous

Module:Shared: Difference between revisions

From Melvor Idle
109 bytes removed ,  22 February 2022
formatnum: Use faster variant of function
(added p.fractionpair)
(formatnum: Use faster variant of function)
Line 151: Line 151:
end
end
   
   
--Stolen from Stack Overflow
--Adds commas
--Adds commas
function p.formatnum(number)
function p.formatnum(number)
local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
if tonumber(number) == nil then
return number
-- reverse the int-string and append a comma to all blocks of 3 digits
else
int = int:reverse():gsub("(%d%d%d)", "%1,")
local result = number
while true do
-- reverse the int-string back remove an optional comma and put the
-- Format in blocks of 3 digits at a time until formatting is complete
-- optional minus and fractional part back
result, k = string.gsub(result, "^(-?%d+)(%d%d%d)", '%1,%2')
return minus .. int:reverse():gsub("^,", "") .. fraction
if k == 0 then
break
end
end
return result
end
end
end