How can I fix my number seperating script?

Sorry if the title isn’t very detailed, I want to make a script so cash will be like “1,434” if its’ digits are between 4 and 6, and numbers between 7 and 10 digits will be like “1,435M” etc. I’ll add it later.
It doesn’t work for some reason, I asked to people, tried to solve myself but I couldn’t fix it.
(No errors)
Cash is being displayed like 100000 instead of 100,000 so it’s not working.

Code:

-- Variables
local frame = script.Parent
local amount = frame.Amount
local cashtext = frame.CashText
local player = game.Players.LocalPlayer
local cash = player:WaitForChild("leaderstats"):WaitForChild("Cash")
local cashLoaded = cash:WaitForChild("Loaded")
-- One time
repeat wait() until cashLoaded
amount.Text = cash.Value
-- Functions
local function tableToString(tablename)
	local strings = ""
	for _, v in pairs (tablename) do
		strings = strings.. tostring(v)
	end
	return strings
end
local function cashChanged(prop)
	if prop == cash.Value then
		local cashamount = tostring(cash.Value)
		if #cashamount >= 4 and #cashamount <= 6 then
			local cashlen = #cashamount
			local tableCash = {}
			for i, v in pairs (string.split(cashamount)) do
				if i == cashlen - 3 then
					table.insert(tableCash, ",") 
				end
				table.insert(tableCash, v)
			end
			local newCash = tableToString(tableCash)
			print(newCash)
			amount.Text = newCash
		end
	end
end
-- Events
cash.Changed:Connect(cashChanged)

The youtuber XxxLloyd061302xxX made a really good video tutorial on this https://www.youtube.com/watch?v=Mov5znC3yOA

1 Like

Dropping the solution here so others can learn too.

-- Variables
local frame = script.Parent
local amount = frame.Amount
local cashtext = frame.CashText
local player = game.Players.LocalPlayer
local cash = player:WaitForChild("leaderstats"):WaitForChild("Cash")
local cashLoaded = cash:WaitForChild("Loaded")
-- Functions
local function cashChanged(prop)
	if prop == cash.Value then
		local cashamount = tostring(cash.Value)
		local cashlen = #cashamount
		if cashlen >= 4 and cashlen <= 6 then
			amount.Text = cashamount:sub(1, cashlen-3) .. "," .. cashamount:sub(cashlen-2, cashlen-2) .. "K+"
		end
	end
end
-- One time
repeat wait() until cashLoaded
cashChanged(cash.Value)
-- Events
cash.Changed:Connect(cashChanged)