Padding 0's to number

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"
local padded = string.format(str, number)

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.

Example of constant leading zeroes
-- 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.

11 Likes