String processing in windows batch files: How to pad value with leading zeros?

There’s a two-stage process you can use:

REM initial setup
SET X=5

REM pad with your desired width - 1 leading zeroes
SET PADDED=0%X%

REM slice off any zeroes you don't need -- BEWARE, this can truncate the value
REM the 2 at the end is the number of desired digits
SET PADDED=%PADDED:~-2%

Now TEMP holds the padded value. If there’s any chance that the initial value of X might have more than 2 digits, you need to check that you didn’t accidentally truncate it:

REM did we truncate the value by mistake? if so, undo the damage
SET /A VERIFY=1%X% - 1%PADDED%
IF NOT "%VERIFY%"=="0" SET PADDED=%X%

REM finally update the value of X
SET X=%PADDED%

Important note:

This solution creates or overwrites the variables PADDED and VERIFY. Any script that sets the values of variables which are not meant to be persisted after it terminates should be put inside SETLOCAL and ENDLOCAL statements to prevent these changes from being visible from the outside world.

Leave a Comment