Put zero in front of a string

Welcome Forums General PowerShell Q&A Put zero in front of a string

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

  • Author
  • #5818

    Points: 0
    Rank: Member

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

    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

    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


    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 $_}


The topic ‘Put zero in front of a string’ is closed to new replies.