1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[PowerShell] Convert 1 digit number to 2 digit number

Discussion in 'HTML, Graphics & Programming' started by HungryHippos, May 26, 2011.

  1. HungryHippos

    Soldato

    Joined: Mar 25, 2004

    Posts: 7,183

    Location: Fareham

    Hi all,

    Is there a way in PowerShell to convert a one digit number to a two digit number?

    For example:

    Code:
    $count = 1..10 ; foreach ($number in $count) {$number}
    
    Loops through numbers 1 to 10 and returns them as values $number.

    when run you get this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    I want this returned instead:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10

    So if number is less than 9 it adds a 0 on the front.

    I was thinking something like:

    Code:
    $count = 1..10 ; foreach ($number in $count)
    	{
    		if ($number -le 9)
    		{
    		$number = "0" + $number
    		}
    	$number
    	}
    If you run this you do get:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10

    But it doesn't seem very elegant, is there a better way?

    Thanks!
     
  2. JHeaton

    Mobster

    Joined: Dec 19, 2009

    Posts: 2,669

    Location: Lancashire

    Code:
    "{0:D2}" -f $number
    The above can be used to format a number and make sure it is at least two digits.
     
  3. HungryHippos

    Soldato

    Joined: Mar 25, 2004

    Posts: 7,183

    Location: Fareham

    Legend thanks! :)

    P.S Knew about the formatting for decimal places didn't know you could add digits with it though
     
  4. JHeaton

    Mobster

    Joined: Dec 19, 2009

    Posts: 2,669

    Location: Lancashire

    Yeah, it's one of those things that seems to be less well-known, here at least. Just got to be a bit careful if you want to add leading zeroes on a floating-point number. :p
     
  5. HungryHippos

    Soldato

    Joined: Mar 25, 2004

    Posts: 7,183

    Location: Fareham

    This is what I was trying to achieve btw, seems to work good now :)

    Code:
    $CurrentDate = Get-Date
    $Time = ""
    [string]$Time = "{0:D2}" -f ($CurrentDate.hour) + ":" + "{0:D2}" -f ($CurrentDate.minute) + ":" + "{0:D2}" -f ($CurrentDate.second)
    
    Just wanted the current time in hours:mins:secs to be consistently 2 digits across em all!