How should I code a 4 digit display?

I am currently making a tally counter item in my game, and I am confused as to how to make a 4 digit display.

For example, if the tally is at count “9”, then it will show “0009”, so it looks like this:
th-3772669326

I am using a screenGUI to show the numbers, and am trying to code a way so that numbers fit into the format above.

Currently, my code is:

local tool = script.Parent.Parent.Parent.Parent
local currentNumber = 0
currentNumberValue = nil

tool.Activated:Connect(function()
	currentNumber = currentNumber+1
	if currentNumber == 9999 then
		currentNumber = 0
	end
	local currentNumberLength = string.len(tostring(currentNumber))
	local fillNumber = 3-currentNumberLength
	if currentNumberValue == nil then
		currentNumberValue = tostring(currentNumber)
	end
	for i=0, fillNumber, 1 do
		currentNumberValue = "0"..tostring(currentNumberValue)
	end
	
	script.Parent.SurfaceGui.TextLabel.Text = currentNumberValue
end)

The way it’s supposed to work is to count the length of the count and how many zeros are needed to fill it in, then fill in the same number of zeros.

So for example, count is “5”, so it is 1 digit long ⇾ 3 zeros needed to fill in

I am looking forward to your advice. Thank you in advance!

via the magic of formatting strings

local number = 9
local str = string.format("%04d", number) -- 0009
1 Like

Woah, I cannot believe I missed this!
Thank you for your insight.