I have made a simple and short function to format numbers to size names(K, M, T, etc.) as you see in many simulator games. Thought to post it here to save yall some time:
--By caching the names and powers the speed of the function is doubled
local names = {"K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dd", "Ud", "Dd", "Td", "Qad", "Qid",
"Sxd", "Spd", "Ocd", "Nod", "Vg", "Uvg", "Dvg", "Tvg", "Qavg", "Qivg", "Sxvg", "Spvg", "Ocvg"}
local pows = {}
for i = 1, #names do table.insert(pows, 1000^i) end
local function formatNumber(x: number): string
--use the absolute value to simplify calculations
local ab = math.abs(x)
--theres no need to convert numbers in the range -1000 < x < 1000
if ab < 1000 then return tostring(x) end
--calculate the power of 1000 to use for division
local p = math.min(math.floor(math.log10(ab)/3), #names)
--calculate result using abs/1000^p and keep 2 decimal digits
local num = math.floor(ab/pows[p]*100)/100
--add back the sign if the number is negative and add the name at end
return num*math.sign(x)..names[p]
end
--example usage
print(formatNumber(123456)) --> 123.45K
print(formatNumber(-12345678)) --> -12.34M
The function currently takes around 2-3 microseconds to run(which is equal to 0.002-0.003 milliseconds).
If anyone has ideas to simplify it even more leave them down below.