Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Formatting numeric results (basic formatting)

0.00/5 (No votes)
8 Jan 2011 1  
Formatting numeric results (basic formatting)
People often struggle to use the right kind of numeric format specifiers. So here is the list of them once again (they can be found in any C# for beginners book) or on msdn.

C[n] - Currency
D[n] - Decimal
E[n] or e[n] - Exponent
F[n] - Fixed point
G[n] - General
N[n] - Number
X[n] or x[n] - Hex

n in all cases are the precision specifiers.

Examples - Compare various output when Console.WriteLine is used with an integer value.
C#
Console.WriteLine("{0:C4}", 5);  //Output $5.0000
Console.WriteLine("{0:D4}", 5);  //Output 0005
Console.WriteLine("{0:E4}", 5);  //Output 5.0000E+000
Console.WriteLine("{0:F4}", 5);  //Output 5.0000
Console.WriteLine("{0:G4}", 5);  //Output 5
Console.WriteLine("{0:N4}", 5);  //Output 5.0000
Console.WriteLine("{0:X4}", 5);  //Output 0005

Comparision when Console.WriteLine is used with a double value.
C#
double l = 5.00;
Console.WriteLine("{0:C4}", l);  //Output $5.0000
Console.WriteLine("{0:N4}", l);  //Output 5.000
Console.WriteLine("{0:G4}", l);  //Output 5
Console.WriteLine("{0:F4}", l);  //Output 5.000
Console.WriteLine("{0:F4}", l);  //Output 5.000

Cheers

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here