StringBuilder and string formatting
Format numbers and text exactly the way you want, and build long strings efficiently with StringBuilder.
Standard numeric formats
| Format | Meaning | `1234.5678` → |
|---|---|---|
F2 | 1234.57 | |
N2 | 1,234.57 | |
N0 | 1,235 | |
E2 | 1.23E+003 | |
P1 | 0.25 → 25.0 % | |
C | ₹1,234.57 (en-IN) | |
D5 | 42 → 00042 | |
X | 255 → FF |
double weight = 1234.5678;int qty = 42; Console.WriteLine(weight.ToString("F2")); // 1234.57Console.WriteLine($"{weight:N1} kg"); // format inside interpolationConsole.WriteLine($"Item {qty:D4}"); // Item 0042Console.WriteLine($"{0.075:P1} tax"); // 7.5 % taxConsole.WriteLine($"{weight:0.0} / {weight:#,##0}"); // custom patterns1234.57 1,234.6 kg Item 0042 7.5 % tax 1234.6 / 1,235
Alignment: making columns
var rows = new[] { ("B1", 6.0, 134.4), ("C12", 3.5, 147.7), ("BR3", 4.24, 31.8) }; Console.WriteLine($"{"Mark",-6}{"Length",8}{"Weight",10}");foreach (var (mark, len, kg) in rows) Console.WriteLine($"{mark,-6}{len,8:F2}{kg,10:F1}");Mark Length Weight B1 6.00 134.4 C12 3.50 147.7 BR3 4.24 31.8
{value,8} right-aligns in 8 characters, {value,-6} left-aligns in 6. Combine with a format: {value,8:F2}.
Why += in a loop is slow
s += "x" can’t change s; it creates a new string containing all of the old text plus the new piece. In a loop of 10,000 iterations that means 10,000 strings and millions of characters copied (switch the diagram to “+ vs StringBuilder”).
StringBuilder
using System.Text; var sb = new StringBuilder();sb.AppendLine("Mark,Length");for (int i = 1; i <= 3; i++){ sb.Append('B').Append(i).Append(',').Append(i * 1.5).AppendLine();}sb.Insert(0, "# Beam list\n");sb.Replace(",", ";"); string csv = sb.ToString(); // build the final string onceConsole.Write(csv);# Beam list Mark;Length B1;1.5 B2;3 B3;4.5
| Use… | When |
|---|---|
+ or interpolation | |
string.Join(", ", items) | |
StringBuilder |
9 x 3 = 27 with the numbers right-aligned in 2 and 3 characters. Print it once at the end.
Show the solution
using System.Text; var sb = new StringBuilder();for (int i = 1; i <= 10; i++) sb.AppendLine($"{9,2} x {i,2} = {9 * i,3}");Console.Write(sb.ToString());9 x 1 = 9 9 x 2 = 18 ... 9 x 10 = 90
Remember
Format with ToString("F2")or$"{x:N2}"; align with{x,8}/{x,-8}.Formats depend on culture; use InvariantCulturefor files and data exchange.Strings are immutable: +=in a loop creates many temporary strings.Use StringBuilderto build text step by step, thenToString()once.