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

前端 未结 7 662
时光取名叫无心
时光取名叫无心 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:43

    OK GUYS i have found a solution, compressing it down as simple as possible.

    @echo off
    title pad numbers
    set num=0
    set zero= 000
    :loop
    @set /a num=%num%+1
    if /i %num% GTR 9 set zero= 00
    if /i %num% GTR 99 set zero= 0
    if /i %num% GTR 999 set zero= 
    echo %zero%%num%
    goto loop
    

    this will display your count up number using 4 digits. but the code can be altered to use 2 digits as shown below.

    @echo off
    title pad numbers
    set num=0
    set zero= 0
    :loop
    @set /a num=%num%+1
    if /i %num% GTR 9 set zero= 
    echo %zero%%num%
    goto loop
    

    if you want to set it as a displayable single variable...

    @echo off
    title pad numbers
    set num=0
    set zero= 0
    :loop
    @set /a num=%num%+1
    if /i %num% GTR 9 set zero= 
    set %zero%%num%=number
    echo %number%
    goto loop
    

    if you want it to count up in seconds...

    @echo off
    title pad numbers
    set num=0
    set zero= 0
    :loop
    @set /a num=%num%+1
    if /i %num% GTR 9 set zero= 
    set %zero%%num%=number
    echo %number%
    ping localhost -n 2 >nul
    goto loop
    

    i hope this was a great help ^^

提交回复
热议问题