Put zero in front of a string

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 7 months ago.

  • Author
    Posts
  • #5818

    by leitsu at 2013-04-17 23:27:07

    Hi
    If I have a string. The string can be any number but needs to be four digits. I need to put zero in front of the string. How do I do that
    For example,
    38 -> 0038
    1234 -> 1234
    1 -> 0001
    100 -> 0100

    by Ernie at 2013-04-17 23:56:36

    One way would be to yse the PadLeft method of the string class as below

    [string[]]$String = "0038","55","430","09"

    $String | foreach {$_.PadLeft(4,'0')}

    Hope that helps
    Ernie

    by Ernie at 2013-04-18 00:00:10

    A little more explanation

    Basically the above code will insert a Zero infront of each string if the said sting is less than four characters long in the first instance

    Ernie

    by mjolinor at 2013-04-18 03:52:45

    Another option is to use a format string.

    38,1234,1,100 |
    foreach {'{0:0###}' -f $_}

    0038
    1234
    0001
    0100

You must be logged in to reply to this topic.