<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Working with data
All lessons in this course

Lesson 28 of 60 13 minIntermediate

StringBuilder and string formatting

Format numbers and text exactly the way you want, and build long strings efficiently with StringBuilder.

Reports, labels, logs and exports are all text. This lesson covers the two skills you need: formatting values (decimals, separators, padding) and building large strings without slowing your program down.

Interactive

Formatting and building strings

Results use CultureInfo.InvariantCulture.
value.ToString("F2")"1234567.89"fixed, 2 decimals
value.ToString("N2")"1,234,567.89"thousands separators
value.ToString("N0")"1,234,568"separators, no decimals
value.ToString("E2")"1.23E+006"scientific
value.ToString("0.000")"1234567.891"custom pattern
value.ToString("#,##0.0")"1,234,567.9"custom with separator
0.4567.ToString("P1")"45.7 %"percent (×100)
1234567.ToString("D6")"1234567"zero-padded integer
1234567.ToString("X")"12D687"hexadecimal
$"|{name,-8}|{qty,5}|" → "|Bolt | 24|" // alignment: - = left, + = right

Standard numeric formats

FormatMeaning`1234.5678` →
F2fixed-point, 2 decimals1234.57
N2number with group separators1,234.57
N0separators, no decimals1,235
E2scientific1.23E+003
P1percent (value × 100)0.25 → 25.0 %
Ccurrency of the current culture₹1,234.57 (en-IN)
D5integer padded with zeros42 → 00042
Xhexadecimal integer255 → FF
Formats.cs
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 patterns
Output
1234.57
1,234.6 kg
Item 0042
7.5 % tax
1234.6 / 1,235

Alignment: making columns

Table.cs
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}");
Output
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

Strings are immutable. 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

Builder.cs
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);
Output
# Beam list
Mark;Length
B1;1.5
B2;3
B3;4.5
Use…When
+ or interpolationjoining a few pieces once
string.Join(", ", items)joining a collection with a separator
StringBuilderbuilding text in a loop or in many steps
Quick check

What does $"{7.5:F3}" produce?

Quick check

Why is StringBuilder faster than += inside a large loop?

Practice

Use a StringBuilder to build a multiplication table for 9 (1 to 10) where each line looks like 9 x 3 = 27 with the numbers right-aligned in 2 and 3 characters. Print it once at the end.

Show the solution
Solution.cs
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());
Output
 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 InvariantCulture for files and data exchange.
  • Strings are immutable: += in a loop creates many temporary strings.
  • Use StringBuilder to build text step by step, then ToString() once.
0 of 60 lessons completed