C# offers several powerful ways to format strings for display, output, and logging.
string msg = string.Format("Hello, {0}! You are {1} years old.", "Alice", 30);
Console.WriteLine(msg);
double price = 1234.5678;
Console.WriteLine(price.ToString("C")); // $1,234.57 (currency)
Console.WriteLine(price.ToString("F2")); // 1234.57 (fixed 2 decimals)
Console.WriteLine(price.ToString("N0")); // 1,235 (number, no decimals)
Console.WriteLine(price.ToString("E2")); // 1.23E+003 (scientific)
Console.WriteLine(price.ToString("P1")); // 123,456.8% (percent)
// Inside interpolation
Console.WriteLine($"{price:C}"); // $1,234.57
Console.WriteLine($"{price:F2}"); // 1234.57
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd")); // 2024-05-01
Console.WriteLine(dt.ToString("dddd, MMMM d, yyyy")); // Wednesday, May 1, 2024
Console.WriteLine(dt.ToString("HH:mm:ss")); // 14:30:00
Console.WriteLine($"{dt:d}"); // Short date: 5/1/2024
Console.WriteLine($"{"Name",-15} {"Score",5}");
Console.WriteLine($"{"Alice",-15} {95,5}");
Console.WriteLine($"{"Bob",-15} {87,5}");
// Name Score
// Alice 95
// Bob 87