Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to add leading zeros to a number value?

I'm making a clock, so far it works perfectly, though one problem is that if the second/minute number is less then 10 it will write it as one number. I want the number to always have two digits.

What I want

1:01:05

What I get

1:1:5

I could do something along the lines of:

if (time):len() == 1 then
	time = "0" .. time
end

But I'm not overly confident in its reliability (I'm extremely picky when it comes to this stuff so it could just be me overreacting), and it takes up a lot of space.

Whats a more sleek/reliable method then an if statement I could use to pull this off?

1 answer

✓ Accepted answer

You could use string.format to do that.

if you use % 02d(remove the space here), it will make the number have 2 digits, for example:

local str = "% 02d" --Remove the spaces here, scripting helpers is for some reason incorrecly formatting code
print(string.format(str, 1)) -- 01

local str = "% 02d:% 02d:% 02d" --Remove the spaces here, scripting helpers is for some reason incorrecly formatting code
print(string.format(str, 1, 10, 35)) -- 01:10:35

If you need any more help, here's the documentation link:

https://developer.roblox.com/en-us/articles/Format-String

2 comments

0

Thanks, also I believe "^%" will stop "%" from reformatting the code.

0

the problem is that, if I use %%, the % shows, but the 02 wont

This discussion is preserved as it was. New answers, comments, and votes are closed.