Menu
CoddyTech

Format Strings

Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 9 of 28.

The -f operator fills a format string. {0} is replaced by the first value after -f, {1} by the second, and so on:

"{0} scored {1} points" -f "Ivy", 87
"{0:N2} km" -f 5
"[{0,-6}][{1,5}]" -f "ab", 42
Ivy scored 87 points
5.00 km
[ab    ][   42]

After a colon comes the number format: N2 is a number with 2 decimals and a thousands separator, N0 a whole number, D3 a whole number padded to 3 digits (007), P0 a percent.

After a comma comes the width. A positive width pads on the left, so numbers line up on the right; a negative width pads on the right, so text lines up on the left. Width and format can go together: {1,8:N2}.

challenge icon

Challenge

Easy

Print a price list whose columns line up.

  1. Every row is a name in a column 8 characters wide, padded on the right, then a price in a column 8 characters wide, padded on the left, with 2 decimals.
  2. Print the header row with the words Item and Price in the same two columns.
  3. Print the rows for Coffee (3.5), Bagel (2.25) and Juice (12).
  4. Print a last row with Total: and the sum of the three prices, computed by the script.

Your script prints:

Item       Price
Coffee      3.50
Bagel       2.25
Juice      12.00
Total:     17.75

Try it yourself

$coffee = 3.5
$bagel = 2.25
$juice = 12
# Print the header, the three rows and the total
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics