Format variable as 4 digits with leading zeroes

后端 未结 4 2092
太阳男子
太阳男子 2020-12-17 10:15

A store number could be 1-4 digits.

Store #26 would be 0026 in respect to how devices are named, but I\'d like to give the techs the ease of being able to type 26 to

相关标签:
4条回答
  • 2020-12-17 10:33

    Adding to other's answers here, if you want to make/change an array of data to have a specific leading zero structure (or any other changes to the data) you can do this:

    $old_array = (0..100)
    $new_array = @()
    $old_array | % { $new_array += "{0:d3}" -f $_}
    
    0 讨论(0)
  • Just to avoid having PetSerAl's useful help go to waste (should the comment be deleted at some point):

    Aside from using the format operator (-f), which I would consider the preferred approach, you can also use formatting methods provided by the respective value.

    • If the value is a string (as it seems to be in your case), you can pad it with zeroes:

      '26'.PadLeft(4, '0')
      
    • If the value is numeric you can format it as a string:

      (26).ToString('0000')
      
    0 讨论(0)
  • 2020-12-17 10:39

    You would use -format operator:

     '{0:d4}' -f $variable
    

    https://ss64.com/ps/syntax-f-operator.html

    the above will work if your variable is an integer, if not you can cast it to integer:

    '{0:d4}' -f [int]$variable
    
    0 讨论(0)
  • 2020-12-17 10:48

    Foreach versions of padleft and tostring. The 0 in the first one has to be quoted:

    '4' | % padleft 4 '0'
    0004
    
    4 | % tostring 0000
    0004
    

    Working with a range:

    1..10 | % tostring 0000
    
    0001
    0002
    0003
    0004
    0005
    0006
    0007
    0008
    0009
    0010
    

    With a prefix:

    1..10 | % tostring COMP0000
    
    COMP0001
    COMP0002
    COMP0003
    COMP0004
    COMP0005
    COMP0006
    COMP0007
    COMP0008
    COMP0009
    COMP0010
    
    0 讨论(0)
提交回复
热议问题