🎨 Format Strings Like a Pro
String.Format() verbose. Concatenation messy. String interpolation with format specifiers = clean & powerful.
Common Format Specifiers
decimal price = 1234.5678m;
DateTime now = DateTime.Now;
int count = 42;
// Currency
Console.WriteLine($"Price: {price:C}");
// Output: Price: $1,234.57
// Fixed decimal places
Console.WriteLine($"Price: {price:F2}");
// Output: Price: 1234.57
// Percentage
Console.WriteLine($"Progress: {0.753:P}");
// Output: Progress: 75.30%
// Date formats
Console.WriteLine($"Date: {now:yyyy-MM-dd}");
// Output: Date: 2024-03-19
Console.WriteLine($"Time: {now:HH:mm:ss}");
// Output: Time: 14:30:45
// Padding
Console.WriteLine($"Count: {count,10}");
// Output: Count: 42 (right-aligned)
Console.WriteLine($"Count: {count,-10}");
// Output: Count: 42 (left-aligned)
📊 Real-World Examples
// Financial report
var revenue = 1234567.89m;
var profit = 234567.89m;
var margin = profit / revenue;
Console.WriteLine($@"
Revenue: {revenue,15:C}
Profit: {profit,15:C}
Margin: {margin,15:P2}
");
// File sizes
long bytes = 1536000;
Console.WriteLine($"Size: {bytes / 1024.0:N2} KB");
// Output: Size: 1,500.00 KB
// Table output
var products = new[] {
("Laptop", 999.99m, 15),
("Mouse", 29.99m, 150)
};
Console.WriteLine($"{'Name',-10} {'Price',10} {'Stock',8}");
foreach (var (name, price, stock) in products)
{
Console.WriteLine($"{name,-10} {price,10:C} {stock,8}");
}
// Name Price Stock
// Laptop $999.99 15
// Mouse $29.99 150
🎯 Format Cheat Sheet
:C– Currency ($1,234.56):D5– Decimal padded (00042):E– Scientific (1.234568E+003):F2– Fixed-point 2 decimals (1234.57):N– Number with commas (1,234.57):P– Percentage (75.30%):X– Hexadecimal (2A)
“Stopped using String.Format entirely. Interpolation with format specifiers is cleaner, faster to write, easier to read. Financial reports look professional now.”
