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.


If you are confident that the number of digits in your original number is always <= 2, then

set "x=0%x%"
set "x=%x:~-2%"

If the number may exceed 2 digits, and you want to pad to 2 digits, but not truncate values larger then 99, then

setlocal enableDelayedExpansion
if "%x%" equ "%x:~-2%" (
  set "x=0%x%"
  set "x=!x:~-2!"
)

Or without delayed expansion, using an intermediate variable

set paddedX=0%x%
if "%x%" equ "%x:~-2%" set "x=%paddedX:~-2%"

The nice thing about the above algorithms is it is trivial to extend the padding to any arbitrary width. For example, to pad to width 10, simply prepend with 9 zeros and preserve the last 10 characters

set "x=000000000%x%"
set "x=%x:~-10%"

TO prevent truncating

set paddedX=000000000%x%
if "%x%" equ "%x:~-10%" set "x=%paddedX:~-10%"