C# String Format

By FoxLearn 12/13/2024 2:19:39 AM   258
In C#, the String.Format method is used to format strings by embedding placeholders within a string and then replacing those placeholders with values.

In C#, we can format strings using three common methods.

C# String Format

The string.Format method is used to create a new formatted string by embedding placeholders (e.g., {0}, {1}, etc.) and replacing them with specified values. It returns the formatted string.

string result = string.Format("Name: {0}, Age: {1}", "Alice", 30);

The Console.WriteLine method formats and prints the formatted string directly to the console. It works similarly to string.Format, but the result is printed rather than returned.

Console.WriteLine("Name: {0}, Age: {1}", "Alice", 30);

The StringBuilder.AppendFormat method is used to append formatted strings to a StringBuilder object. It is particularly useful for building strings incrementally, especially in performance-critical scenarios where string concatenation can be inefficient.

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Name: {0}, Age: {1}", "Alice", 30);
string result = sb.ToString();

C# String Format Numeric Data

C# provides several standard format specifiers that you can use to format numeric values.

For example, C# Format Currency (C)

double amount = 1234.56;
string formatted = string.Format("{0:C}", amount); // Output: $1,234.56

The C specifier formats the number as a currency value, using the current culture's currency symbol.

For example, C# Format Decimal (D)

int number = 42;
string formatted = string.Format("{0:D5}", number); // Output: 00042 (padded to 5 digits)

The D specifier formats the number as a decimal integer. You can specify the minimum number of digits.

For example, C# Format Fixed-Point (F)

double value = 123.4567;
string formatted = string.Format("{0:F2}", value); // Output: 123.46 (rounded to 2 decimal places)

The F specifier formats the number as a fixed-point number. You can specify the number of decimal places.

For example, C# Format Number (N)

double value = 1234567.89;
string formatted = string.Format("{0:N2}", value); // Output: 1,234,567.89 (with 2 decimal places)

The N specifier formats the number with thousands separators and a specified number of decimal places.

For example, C# Format Percentage (P)

double percentage = 0.2567;
string formatted = string.Format("{0:P1}", percentage); // Output: 25.7% (formatted to 1 decimal place)

The P specifier formats the number as a percentage. It multiplies the number by 100 and adds a percentage symbol.

For example, C# Format Scientific (E)

double value = 12345.6789;
string formatted = string.Format("{0:E2}", value); // Output: 1.23E+004 (scientific notation with 2 decimal places)

C# also allows custom numeric format strings for more control over how numbers are displayed.

For example, C# Custom Decimal Places

double value = 123.4567;
string formatted = string.Format("{0:0.000}", value); // Output: 123.457 (rounded to 3 decimal places)

The dot (.) custom format specifier inserts a localized decimal separator, while the comma (,) specifier adds a group separator.

double val = 1253634.21255754;
var f1 = string.Format(CultureInfo.InvariantCulture, "{0:#,#.##}", val);
var f2 = string.Format(CultureInfo.InvariantCulture, "{0:0.0000}", val);
Console.WriteLine(val); // 1253634.21255754
Console.WriteLine(f1); // 1,253,634.21
Console.WriteLine(f2); // 1253634.2126

0: Displays digits and pads with zeros. "00000" will pad the number to ensure it has at least 5 digits.

#: Placeholder for optional digits (only displays non-zero digits). "{0:#.##}" formats the number with up to two decimal places, but it won't show unnecessary zeros.

%: Percentage format. "{0:0.0%}" displays a number as a percentage with one decimal place.

double number1 = 1234.5678;
Console.WriteLine(string.Format("{0:C}", number1));  // $1,234.57
Console.WriteLine(string.Format("{0:F2}", number1)); // 1234.57
Console.WriteLine(string.Format("{0:N}", number1));  // 1,234.57
Console.WriteLine(string.Format("{0:P}", 0.25));     // 25.00%
Console.WriteLine(string.Format("{0:E}", number1));  // 1.234568E+003
Console.WriteLine(string.Format("{0:0.00}", 12));   // 12.00

Console.WriteLine("{0}  {1, 12}", "Decimal", "Hexadecimal");
Console.WriteLine("{0:D}  {1,8:X}", 501, 547);
Console.WriteLine("{0:D}  {1,8:X}", 345, 766);
Console.WriteLine("{0:D}  {1,8:X}", 326, 655);
Console.WriteLine("{0:D}  {1,8:X}", 125, 833);
Console.WriteLine("{0:D}  {1,8:X}", 622, 452);

Output:

Decimal   Hexadecimal
501       223
345       2FE
326       28F
125       341
622       1C4

The {0:D} format item formats the first item as a decimal. The {1,8:X} format item formats the second item as a hexadecimal, with a width of 8 characters. Since the number has only three digits, it is right-aligned and padded with spaces.

C# String Format Alignment

The alignment (or length) field specifies the minimum number of characters in the output. A positive value, like {0,10}, right-aligns the output, while a negative value, like {0,-10}, left-aligns it.

static void Main(string[] args)
{
    Console.WriteLine(1);
    Console.WriteLine(15);
    Console.WriteLine(1555);
    Console.WriteLine(15567);
    Console.WriteLine(156201);

    Console.WriteLine("{0,10}", 1);
    Console.WriteLine("{0,10}", 13);
    Console.WriteLine("{0,10}", 1555);
    Console.WriteLine("{0,10}", 15567);
    Console.WriteLine("{0,10}", 156201);
}

Output:

1
15
1555
15567
156201
         1
        13
      1555
     15567
    156201

We print five numbers without specifying the field length, so the output length matches the number of characters. In the second case, with a field length of 10, each number is padded to a minimum of ten characters and right-aligned.

C# String Format Date and Time

static void Main(string[] args)
{
    var dateTime = DateTime.Now;
    Console.WriteLine("Short date: {0:d}", dateTime); // Short date: 12/13/2024
    Console.WriteLine("Long date: {0:D}", dateTime); // Long date: Friday, December 13, 2024
    Console.WriteLine("Short time: {0:t}", dateTime); // Short time: 9:16 AM
    Console.WriteLine("Long time: {0:T}", dateTime); // Long time: 9:16:27 AM
    Console.WriteLine("Month: {0:M}", dateTime); // Month: December 13
    Console.WriteLine("Year: {0:Y}", dateTime); // Year: December 2024
}

The code example demonstrates six different formats for displaying the current date and time.