Appendix C. Format Specifiers

Table C-1 lists the numeric format specifiers supported by the ToString method on the predefined numeric types (see Chapter 3).

Table C-1. Numeric format specifiers

Specifier

String result

Data type

C[n]

$XX,XX.XX

($XX,XXX.XX)

Currency

D[n]

[-]XXXXXXX

Decimal

E[n] or e[n]

[-]X.XXXXXXE+xxx

[-]X.XXXXXXe+xxx

[-]X.XXXXXXE-xxx

[-]X.XXXXXXe-xxx

Exponent

F[n]

[-]XXXXXXX.XX

Fixed point

G[n]

General or scientific

General

N[n]

[-]XX,XXX.XX

Number

P[n]

[-]XX,XXX.XX %

Percent

R

Round-trip format

Floating point

X[n] or x[n]

Hex representation

Hex

This is an example that uses numeric format specifiers without precision specifiers:

using System;
class TestDefaultFormats {
  static void Main(  ) {
    int i = 654321;
    Console.WriteLine("{0:C}", i); // $654,321.00
    Console.WriteLine("{0:D}", i); // 654321
    Console.WriteLine("{0:E}", i); // 6.543210E+005
    Console.WriteLine("{0:F}", i); // 654321.00
    Console.WriteLine("{0:G}", i); // 654321
    Console.WriteLine("{0:N}", i); // 654,321.00
    Console.WriteLine("{0:P}", i); // 65,432,100.00 %
    Console.WriteLine("{0:P}", .42); // 42.00 %
    Console.WriteLine("{0:X}", i); // 9FBF1
    Console.WriteLine("{0:x}", i); // 9fbf1
    // Round-trip conversions
    string s1 = Math.PI.ToString("G");
    Console.WriteLine(s1); // 3.14159265358979
    string s2 = Math.PI.ToString("R");
    Console.WriteLine(s2); // 3.1415926535897931
    Console.WriteLine(Math.PI == Double.Parse(s1)); // False
    Console.WriteLine(Math.PI == Double.Parse(s2)); // True
  }
}

This is an example that uses numeric format specifiers with ...

Get C# Essentials, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.