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

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

    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%"
    
    0 讨论(0)
提交回复
热议问题