User Tools

Site Tools


notes:csharp:formatting

Formatting in C#

Numbers

  • C - Local currency
  • D - Decimal (can be used to pad a number with zeroes)
  • E - Exponential (scientific)
  • F - Fixed-point
  • N - Locale-specific number
  • G - General (uses E or F depending on which is more compact)
  • P - Percent
  • X, x - hexadecimal
88.8        C   $88.80
99989.987   C   $99,989.99
888.8       C4  $888.8000
12345       D   12345
12345       D9  000012345
88          D5  00088
888.8       E   8.888000E+002
99999.76543 e   9.999977e+004
99999.76543 e3  1.000e+005
789.1234    E2  7.89E+002
888.8888    F3  888.889
99999.9999  F3  100000.000
99999.9999  F4  99999.9999
99999.9999  F5  99999.99990
99999.9999  F0  100000
99999.99    N   99,999.99
8888888.8   N   8,888,888.80
0.231       P   23.10 %
58739       X   E573
58739       x   e573
13          X2  0D
13          x2  0d
13          x8  0000000d
// Specify values for formatting as an array.
object[] arr = {"Hello", 4, "words", 99.99933};
string str = String.Format("Some values: {0}, {1}, {2}, {3}", arr);
 
// Format currency using a specific culture.
double amount = 54300.12;
Console.WriteLine(amount.ToString("C", new System.Globalization.CultureInfo("en-US"))); // $54,300.12
 
// Format currency using C#6 formatting.
double amount = 800.5;
Console.WriteLine($"{amount:C}");
 
// Specify a minimum width. It's useful for aligning columns.
Console.WriteLine("{0,5:D}", 13);  // displays ...13 where dots represent spaces
Console.WriteLine("{0,-5:D}", 13); // displays 13...
 
// Specify a placeholder.
Console.WriteLine("{0:#.00}", 0.231); // .23
Console.WriteLine("{0:#.00}", 0.237); // .24
 
// Insert leading zeroes.
Console.WriteLine("{0:00000}", 13); // 00013
notes/csharp/formatting.txt · Last modified: 2016/11/28 by admin