Practical .NET · Lesson 6

Text formats

Alignment and format strings line up a table.

How it works

Inside an interpolation hole, a comma sets the width and a colon sets the format. {name,-8} pads the name to 8 characters on the left. {amount,7:0.00} right-aligns the amount in 7 characters with two decimals. string.Join puts a separator between items, so the last item gets no trailing comma.

A working example

var rows = new[] { (Name: "Coffee", Amount: 3.5m), (Name: "Lunch", Amount: 12m), (Name: "Taxi", Amount: 18.25m) };

foreach (var (name, amount) in rows)
{
    Console.WriteLine($"{name,-8}{amount,7:0.00}");
}

Console.WriteLine(string.Join(", ", rows.Select(r => r.Name)));

Expected output

Coffee     3.50
Lunch     12.00
Taxi      18.25
Coffee, Lunch, Taxi
Try this
A negative width pads on the right side of the text.