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

前端 未结 7 696
时光取名叫无心
时光取名叫无心 2020-11-27 19:07

in a Windows cmd batch file (.bat), how do i pad a numeric value, so that a given value in the range 0..99 gets transformed to a string in the range \"00\" to \"99\". I.e. I

7条回答
  •  广开言路
    2020-11-27 19:34

    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.

提交回复
热议问题