I want to add a 0 behind a number x amount of times

Example:

``````local number = 53
-- Assume paddingDigits is 4, I want this:
number = 000053

-- Assume paddingDigits is 3, I want this:
number = 00053
``````

How do I do this? Any help is appreciated!

I’m confused, what is this for? You don’t want the number to be in decimal format?

``````local paddingAmount = 5
``````
2 Likes

Wow the code that you gave worked perfectly! I am using this for sorted maps so I can sort my keys correctly

1 Like

Another way to do this if you wanted the amount of digits with any padded number to remain constant would be

``````local length = 5
local str = "%0"..length.."i"
``````

The result would be that every integer would have zeroes added before it until its total length is 5. If its length was greater than For example

``````     0 -> 00000
5 -> 00005
12 -> 00012
128 -> 00128
2048 -> 02048
12345 -> 12345
123456 -> 123456
``````

If this is for sorting, this method will probably work better, as adding a constant number of zeroes irrespective of how many digits a number has will cause some issues when sorting alphabetically.

``````-- Sorted alphabetically when the number of leading zeroes is always 3
0001
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
0002
00020
00021
``````

Note that 0001 and 0002 are not next to each other.

Example of constant number length
``````-- Using the same numbers as in the previous example
0001
0002
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
``````

Note that using this format, 0001 and 0002 are the first two elements and 0010 only comes after 0002. (Or 0009 if we had it here)

If on the other hand you’re sorting based on value of the number itself, adding leading zeroes isn’t useful.

1 Like

I do not understand what you mean, @C_Sharper’s example adds a fixed amount digits behind the number and your code is doing the same thing. I have a limit on how many digits a number can have so there will be no case where a number has a higher length than 5.