在Windows cmd批处理文件(.bat)中,如何填充数值,使0..99范围内的给定值变换为范围“00”至“99”的字符串。即我想要使零的值超过10的前导零。
您可以使用两个阶段的过程:
@H_301_5@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%
现在TEMP持有填充值。如果X的初始值有可能超过2位数,则需要检查您是否意外截断它:
@H_301_5@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%重要的提示:
此解决方案创建或覆盖变量PADDED和VERIFY。任何设置变量值不会在终止后被持久化的脚本应放在SETLOCAL和ENDLOCAL语句中,以防止这些变化从外界看到。