Here’s another, slightly more flexible way of doing it. It also allows you to have decimals and suffixes, to have e.g. 5.31 M
, giving the user slightly more information.
function floorTo(n, to)
return math.floor(n/to)*to
end
function formatNumberSuffixes(n)
local expSuffixes = {{-3, 'm'}, {-2, 'c'}, {0, ''}, {3, 'k'}, {6, 'M'}, {9, 'B'}}
local lowestExponent = -6
local highgestExponent = math.floor(math.log(n, 10))
local suffix, exponent, prevExponent = '', lowestExponent, lowestExponent
for _, expSuffix in pairs(expSuffixes) do
if expSuffix[1] <= highgestExponent then
prevExponent = exponent
exponent = expSuffix[1]
suffix = expSuffix[2]
end
end
local nSignificant = floorTo(n, 10^prevExponent)
local formatted = tostring( nSignificant / (10^(exponent)) )
repeat
local lastChar = formatted:sub(formatted:len())
if lastChar == '0' or lastChar == '.' then
formatted = formatted:sub(1, formatted:len()-1)
end
until lastChar ~= '0' and lastChar ~='.'
return formatted .. " " .. suffix
end
And a snippet for testing it
for exp = -3, 10 do
local n = 10^exp
if exp > 0 then
n = n + floorTo(math.random()*10^exp, 10^-1)
elseif exp < 0 then
n = n + floorTo(math.random()*10^exp, 10^(exp-2))
end
local nFormatted = formatNumberSuffixes(n)
print(n .. " m =>", nFormatted .. "m")
end
To be clear it’s not better than the earlier reply, I just wanted to play around with the idea and this is what I got.
Also, if you want to work really big numbers (> 2^32) you’ll need to find a bignum library for Lua.