c# · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Format strings and make tidy tables.
A tells C# how a number should look as text. price.ToString("0.00") always shows two decimal places, so 2.5 becomes 2.50. Inside $"...", write it after a colon: {price:0.00}. N0 adds commas between thousands, like 1,234,567.
Alignment pads a value with spaces to a fixed width, so columns line up. {total,6} pads on the left to 6 characters, which suits numbers. {name,-10} pads on the right, which suits text. Put both together: {price,6:0.00}.
Outside $"...", and PadLeft do the same padding.
using System;
string[] items = { "Tea", "Flapjack", "Soup" };
decimal[] prices = { 2.5m, 1.75m, 4m };
decimal total = 0;
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine($"{items[i],-10}{prices[i],6:0.00}");
total = total + prices[i];
}
Console.WriteLine("----------------");
Console.WriteLine($"{"Total",-10}{total,6:0.00}");
Console.WriteLine($"{1234567:N0} visitors so far"); A minus sign means pad on the right; no sign means pad on the left.
guess first
Three brackets, three formats. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
double km = 3.14159;
Console.WriteLine($"[{km:0.0}] [{km,8:0.00}] [{"run",-5}]");
your turn
Your turn. Print a tidy receipt.
On line 7, pad each name on the right to 14 characters, and show each cost with two decimal places. Press run.
output
press run to see what happens
fix it
The scoreboard names are pushed to the right. Fix it!
output
press run to see what happens
- The names line up on the right, like the numbers. Which way does a plain width of 10 pad?
- A width with no sign pads on the left. Text reads better padded on the right.
- Change
{players[i],10}to{players[i],-10}on line 7, then press run.
nailed it
your output lines up perfectly. :D
0.00shows two decimal places,N0adds commas.{value,8}pads left,{value,-8}pads right.PadRightandPadLeftpad any string.
new words in your collection
- format string
- alignment
- PadRight
This lesson isn’t saved. A free account remembers every lesson you finish.