Simple and short function for number abbreviations

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.

13 Likes

I suggest using string interpolation, something like this

`{num*math.sign(x)}{names[p]}`

and it’s only available to one script, I suggest creating a BindableFunction or a ModuleScript so it can be used in any script

I even have a post on this, which very well simplifies it and with good amount of performance (not comparing)

local short = {"", "K", "M", "B", "T"} -- Add more

local function abbrievateNum(number)
local str = tostring(math.floor(number))
return string.sub(str, 1, ((#str+2)%3) + 1)..short[math.floor((#str-1)/3) + 1]
end

If you wish, I’ll personally DM you so that people don’t consider my code instead of yours, I don’t want to get criticised for like ruining or promoting my code and all that stuff.

It is just a way as you asked.

That’s not the case, I welcome all replies as they may be useful for different use cases.

Also, your code is string operation based were mine is math based which means it kind of tackles the problem from a different point of view. Also, correct me if I’m wrong, but I think your code doesn’t handle the case of a really large number being passed to the function(larger than the names provided in short)

1 Like

Yep, that’s right, you need to write more names for more big numbers.