How to add a "k" after coins reach a thousand

I have actually done something like this before in a game I made.

This is an old way I did it many months back and I will probably try a better way. But it works anyway.

This only registers values over 1 million, but I bet you could modify it so that it registers values over 1k

if money >= 1000000 and money <= 10000000 then
	local str = "$"..string.sub(money,1,1).."."..string.sub(money,2,2).."m"
	label.Text = str
elseif money >= 10000000 and money <= 100000000 then
	local str = "$"..string.sub(money,1,2).."."..string.sub(money,3,3).."m"
	label.Text = str
elseif money >= 100000000 and money <= 1000000000 then
	local str = "$"..string.sub(money,1,3).."."..string.sub(money,4,4).."m"
	label.Text = str
end

Instead of the function v1, which at times leaves only the most significant digit visible, you could use a function like this:

local abbrev = {"", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc"}
function abbrevNumber(n: number): string
	
	local digits = math.floor(math.log10(n)) + 1
	local abbrevIndex = math.ceil(digits / 3)
	local numberAbbrev = abbrev[abbrevIndex]
	
	local leftDigits, rightDigits, reducedNum
	if digits > 3 then
		
		leftDigits = (digits - 1) % 3 + 1
		reducedNum = n / math.pow(10, digits - leftDigits)
		rightDigits = 3 - leftDigits
	else
		
		leftDigits = digits
		rightDigits = 0
		reducedNum = n
	end
	
	local formatString = string.format("%%%d.%df%%s", leftDigits, rightDigits)
	local newNumber = string.format(formatString, reducedNum, numberAbbrev)
	return newNumber
end



for i = 0, 12 do
	print(abbrevNumber(10 ^ i))
end


--// output:
--[[

1
10
100
1.00K
10.0K
100K
1.00M
10.0M
100M
1.00B
10.0B
100B
1.00T


]]

Then, instead of checking the leader stats every wait() interval, you can make the code more efficient by only changing TextLabel.Text when the Money Value has been changed.

local abbrev = {"", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc"}
function abbrevNumber(n: number): string
	
	local digits = math.floor(math.log10(n)) + 1
	local abbrevIndex = math.ceil(digits / 3)
	local numberAbbrev = abbrev[abbrevIndex]
	
	local leftDigits, rightDigits, reducedNum
	if digits > 3 then
		
		leftDigits = (digits - 1) % 3 + 1
		reducedNum = n / math.pow(10, digits - leftDigits)
		rightDigits = 3 - leftDigits
	else
		
		leftDigits = digits
		rightDigits = 0
		reducedNum = n
	end
	
	local formatString = string.format("%%%d.%df%%s", leftDigits, rightDigits)
	local newNumber = string.format(formatString, reducedNum, numberAbbrev)
	return newNumber
end

local player = game:GetService("Players").LocalPlayer
local leaderstats = player:WaitForChild("leaderstats")
local moneyValue = leaderstats:WaitForChild("Money")
local textLabel = script.Parent.TextLabel

moneyValue.Changed:Connect(function()

    local value = money.Value
    textLabel.Text = abbrevNumber(value)
end)
1 Like