Numeric Format Strings

In the previous section, we covered string placeholders and learned two implementation approaches. Beyond these two methods, C# also supports more sophisticated formatting rules.

Basic Syntax for Format Placeholders

{index,alignment:format}
1. index

Index / interpolated variable, required field

Traditional numeric placeholders: Console.WriteLine(“{0}”, 123); inserts the value 123 inside {0}

String interpolation with $"": Directly write variable names without numeric indices, for example Console.WriteLine($”Tom is {age} years old”)

Example

int money = 1000;
Console.WriteLine("Raw value: {0}", money);
Console.WriteLine("Currency: {0:C}", money);
Console.WriteLine("Right-aligned currency with 10-character width: |{0,10:C}|", money);Code language: JavaScript (javascript)
Raw value: 1000
Currency: $1,000.00
Right-aligned currency with 10-character width: | $1,000.00|Code language: JavaScript (javascript)

Interpolation equivalent

int money = 500;
Console.WriteLine($"Raw value: {money}");
Console.WriteLine($"Currency: {money:C}");
Console.WriteLine($"Right-aligned currency with 10-character width: |{money,10:C}|");Code language: JavaScript (javascript)
2. alignment

Alignment specifier, optional, separated by comma ,

Purpose: Sets the minimum output character width and horizontal alignment

Example: Console.WriteLine(“{0,10}”, 123); // Occupies 10 character slots, value right-aligned

As you can see, multiple blank spaces appear to the left of 123. The number 10 defines a total width of ten characters, meaning seven empty spaces are padded before 123 to achieve right alignment.

Positive integer: Right alignment; fill empty space on the left with spaces Example: {0,10} → 10-character width, value aligned right

Negative integer: Left alignment; fill empty space on the right with spaces Example: {0,-10} → 10-character width, value aligned left

Let’s modify the code as shown below

Console.WriteLine("{0,-10}", 123);  // Takes up 10 character slots; negative value forces left alignmentCode language: JavaScript (javascript)

The alignment effect might be hard to spot visually. We can add vertical bars to distinguish whitespace clearly

Console.WriteLine("|{0,-10}|", 123);
Console.WriteLine("|{0,10}|", 456);Code language: JavaScript (javascript)

With vertical bar delimiters, the behavior becomes intuitive. The value 10 sets a fixed 10-character width: negative values left-align content, positive values right-align content, with whitespace filling any unused slots.

The equivalent interpolation syntax is shown below

int one = 123;
int two = 456;
Console.WriteLine($"|{one,-10}|");
Console.WriteLine($"|{two,-10}|");Code language: JavaScript (javascript)
3. format

Format specifier segment, optional, separated by colon :

Controls numeric output styles including currency, fixed decimals, scientific notation, hexadecimal and more

Format segment structure :Axx

  • : Must attach directly to the placeholder with no whitespace
  • A: Single-letter format specifier (9 built-in standard formats; case-sensitive for some types)
  • xx: Precision specifier (optional, 1–2 digits; meaning varies based on the format letter)
// F4: Fixed-point format with four decimal places retained
Console.WriteLine("{0:F4}", 12.345678);

// Equivalent interpolation syntax
Console.WriteLine($"{12.345678:F4}");Code language: JavaScript (javascript)

More demonstration samples

double myDouble = 12.345678;
Console.WriteLine("{0,-10:G} -- General", myDouble);      // 12.345678 -- General
Console.WriteLine("{0,-10} -- Default", myDouble);         // 12.345678 -- Default
Console.WriteLine("{0,-10:F4} -- Fixed Point", myDouble);   // 12.3457  -- Fixed Point
Console.WriteLine("{0,-10:C} -- Currency", myDouble);     // $12.35    -- Currency
Console.WriteLine("{0,-10:E3} -- Sci. Notation", myDouble);//1.235E+001 -- Sci. Notation
Console.WriteLine("{0,-10:x} -- Hex integer", 1194719);   // 123adf    -- Hex integerCode language: JavaScript (javascript)

Reference Table for 9 Standard Numeric Format Specifiers

IdentifierNameFunctionPrecision DefinitionSample Output
C/cCurrencyDisplays localized currency symbolNumber of decimal places{0:C} 12.5 → $12.50
D/dDecimal IntegerFor integer types only; pads leading zerosMinimum digit count{0:D4} 12 → 0012
F/fFixed-pointFixed decimal place countDecimal digits to retain{0:F4} 12.345678 →12.3457
G/gGeneralAuto-selects fixed or scientific notation; default formatSignificant digit count{0:G4} 12.345678 →12.35
X/xHexadecimal (case-sensitive)Hex output; X uppercase, x lowercaseMinimum digit count{0:x} 180026 → 2bf3a
N/nNumberComma thousands separatorsDecimal places{0:N2} 12345678.54321 →12,345,678.54
P/pPercentMultiply value by 100 and append %Decimal places{0:P2} 0.1221897 →12.22 %
R/rRound-tripFormat without precision loss for reverse parsingPrecision ignored{0:R} 1234.21897 →1234.21897
E/eScientific Notation (case-sensitive)Exponential notation; E uppercase, e lowercaseDecimal digits for mantissa{0:e4}12.3456789 →1.2346e+001

Leave a Reply

Your email address will not be published. Required fields are marked *