Feedback on my leaderboard cash abbreviation script

Sup, I’m looking for feedback on my leaderboard cash abbreviation script. Say for example your cash is 3759214. To know how much money you have, you need to count the numbers, which is quite annoying, so I’ve made an abbreviation that script turns that number into 3.7M. Now you can see how much money you’ve got at a glance.

I’ve seen other people use math, lookup tables, and all that, but here’s me just using if statements. I was wondering if my method is inefficient or if it’s just fine.

The script: localscript

plr = game.Players.LocalPlayer

local cash = plr:WaitForChild("plrStats"):WaitForChild("cash")

local function shortenFunc(ca) --  ca = cash
	local c = string.split(tostring(ca), "")
	if c == c then
		if ca >= 1000000000 or ca < 1000 then -- we're only looking to abbreviate numbers between a billion and a thousand
			return ca
		elseif ca >= 100000000 then
			if c[3] ~= "0" then
				return "$"..c[1]..c[2]..c[3].."."..c[4].."M"
			else
				return "$"..c[1]..c[2].."M"
			end
		elseif ca >= 10000000 then
			if c[3] ~= "0" then
				return "$"..c[1]..c[2].."."..c[3].."M"
			else
				return "$"..c[1]..c[2].."M"
			end
		elseif ca >= 1000000 then
			if c[2] ~= "0" then
				return "$"..c[1].."."..c[2].."M"
			else
				return "$"..c[1].."M"
			end
		elseif ca >= 100000 then
			if c[3] ~= "0" then
				return "$"..c[1]..c[2]..c[3].."."..c[4].."K"
			else
				return "$"..c[1]..c[2].."K"
			end
		elseif ca >= 10000 then
			if c[3] ~= "0" then
				return "$"..c[1]..c[2].."."..c[3].."K"
			else
				return "$"..c[1]..c[2].."K"
			end
		elseif ca >= 1000 then
			if c[2] ~= "0" then
				return "$"..c[1].."."..c[2].."K"
			else
				return "$"..c[1].."K"
			end
		end
	end
end

local function updateFunc()
	script.Parent.Text = shortenFunc(cash.Value)
end

cash:GetPropertyChangedSignal("Value"):Connect(function()
	updateFunc()
end)

repeat wait() until cash ~= nil
updateFunc()

There’s definitely more short and simple methods of doing this out there, even though yours might work flawlessly. For example:

local Suffixes = {"K", "M", "B", "T", "Q"} 
local function toSuffixString(Number)
	local i = math.floor(math.log(Number, 1e3))
	local v = math.pow(10, i * 3)
	return ("%.1f"):format(Number / v):gsub("%.?0+$", "") .. (Suffixes[i] or "")
end
print(toSuffixString(3700000))
-- Console: "3.7M"

This is definitely a much more concise way of doing this. But, if you’re asking in terms of performance, the difference is probably too miniscule to even worry about. Your way of doing if statements isn’t really taxing on performance and shouldn’t be an issue. Yours might even be faster if you run a benchmark. Only issue is readability.

Credit: Most efficient way of converting a number in scientific notation into a Suffix and back? - #3 by woot3

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.