Working with Numbers

Sometimes you have a number that you need to convert to a string or output in a specific way. Personally I don't think PowerShell handles this very well to be honest but here are some examples:
"{0:N0}" -f 123456.789 returns 123,456
"{0:N2}" -f 123456.789 returns 123,456.79
"{0:C2}" -f 123456.789 returns £123,456.79 (depending on your locale of course)
"{0:P2}" -f 0.12345 returns 12.35 %
"{0:D0}" -f 123456 returns 123456
"{0:D2}" -f 123456 returns 123456
"{0:D8}" -f 123456 returns 00123456
"{0:X8}" -f 123456 returns 0001E240
Hopefully you can see the pattern, the letter stands for Number (floating point), Currency, Percentage, Decimal or Hexadecimal and the number refers to digits, before the decimal point, or after in the case of Number and Currency. Clearly you can pass in variables instead of the values shown above. See Windows PowerShell Tip: Formatting Numbers for further details.

Another way to format a number is as follows:
$a = 5
$b = 1234567
$a.ToString('000') returns 005
$a.ToString('#.00') returns 5.00
$b.ToString('#,###') returns 1,234,567 (this cleverly knows you want a thousands separator)
Now, you might want leading space characters, not leading zeros, in which case you need to use a string method as follows:
($a.ToString(#.0)).PadLeft(10) returns [       5.0]
($b.ToString(#.0)).PadLeft(10) returns [ 1234567.0]