Here’s a quick module I threw together for one of my games!
--[[
Returns a human-readable, abbreviated number from the given <em>number</em>
<strong>number:</strong> The number to format
<strong>numberOfDecimals: </strong> The number of decimals that should be included
]]
function Format.AbbreviateNumber(number: number, numberOfDecimals: number): string
local negative = number < 0
number = math.abs(number)
if number < 1000 then
return (negative and "-" or "") .. tostring(number)
end
for i, suffix in Format.Suffixes do
if number < 10^(3 * i) then
local abbreviatedNumber = number / 10^(3 * (i - 1))
local formatString = "%." .. (numberOfDecimals or 0) .. "f"
abbreviatedNumber = string.format(formatString, abbreviatedNumber)
return (negative and "-" or "") .. abbreviatedNumber .. suffix
end
end
return (negative and "-" or "") .. string.format("%e", number)
end
--[[
Returns a human-readable, comma separated number from the given <em>number</em>
<strong>number:</strong> The number to format
]]
function Format.AddCommasToNumber(number)
local minus, int, fraction = tostring(number):match('([-]?)(%d+)([.]?%d*)')
int = int:reverse():gsub("(%d%d%d)", "%1,"):reverse():gsub("^,", "")
return minus..int..fraction
end
From here you just need to add a check to see if the number is under 1B, and if it is then return .AddCommasToNumber() instead
function formatNumber(n)
if n >= 1e9 then
return string.format("%.2fB", n / 1e9)
elseif n >= 1e6 then
return string.format("%.2fM", n / 1e6)
else
local formatted = tostring(n):reverse():gsub("(%d%d%d)", "%1,"):reverse()
return formatted:sub(1, 1) == "," and formatted:sub(2) or formatted
end
end
t=formatNumber(543000000)
print(t)
t=formatNumber(5430000000)
print(t)
The common way is to reverse a number, pattern match for every 3 digits and replace that with the match plus a comma at the end, reverse it again, then remove any leading comma if one exists.
im kinda confused what you mean, but i’ll take a guess:
make an if statement to check if the number is under 1b, if it is, use the add commas function, if its over 1b, use the abbreviate function, and just use string.gsub() to replace the periods with commas?