×

c# · level 2 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.