Thursday, September 22, 2011

Format Specifier in C#

By and large there are two type of format specifiers in C# / .NET world : Standard Format Specifier and Custom Format Specifier. This post summarizes frequently used format specifiers.


The general syntax for output formatter does look like this:

{n, w:tp}
      n: argument number
      w: width
      t: data type
      p: precision

      ex)  string.Format("{0,9:N2}", v);

The below format specifiers are frequently used by developers.

Standard Format Specifiers for Numeric Type

(Case insensitive)
C : Currency
      string.Format("{0:C}", 1234567) => $1,234,567
D : Decimal
      string.Format("{0:D7}", 123456) => 0123456
E : Scientific
      string.Format("{0:E}", 12345.6) => 1.23456E+004
F : Fixed point
      string.Format("{0:F3}",12345.6) => 12345.600
N : Number
      string.Format("{0:N2}",1234.567)=> 1,234.57
X : Hexadecimal
      string.Format("{0:X}", 255) => FF

Standard Format Specifiers for DateTime Type

d : Short date
     string.Format("{0:d}", today) => 11/21/2011
D : Long date
     string.Format("{0:D}", today) => Firday, July 5, 2010
t : Short time
     string.Format("{0:t}", today) => 4:05 PM
T : Long time
     string.Format("{0:T}", today) => 4:05:55 PM
g : General datetime (short time)
     string.Format("{0:g}", today) => Firday, July 5, 20104:05:55 PM
G : General datetime
     string.Format("{0:g}", today) => Firday, July 5, 20104:05:55 PM

Custom Format Specifiers for Numeric Type

# : Digit placeholder (no leading zeros)
0 : Zero placeholder (w/ leading zeros)
. : Decimal point
, : Thousands operator
; : Section separator

ex)
   val = 12345;
   string.Format("{0:#,##0;(#,##0)}", val)
   => 12,345

   val = -12345;
   string.Format("{0:#,##0;(#,##0)}", val)
   => (12,345)

   val = 0;
   string.Format("{0:#,##0;(#,##0);Zero}", val)
   => Zero

Custom Format Specifiers for DateTime Type

M   : Month. Single digit for <10
MM  : Two digit month
MMM : Abbreviated name of the month
d   : Day. Single digit
dd  : Two digit day
ddd : Abbreviated name of the day
yy  : Two digit year 
yyyy: Four digit year
h   : Hour (12hr)
hh  : Two digit hour (12hr)
H / HH : Hour (24 hr)
m   : Minute
mm  : Two digit minute
s   : Second
ss  : Two digit second
tt  : AM / PM
ex) string.Format("{0:yyyy/MM/dd}", DateTime.Today) => 2011/11/22

2 comments:

  1. what can I do if I need to display the time format in 0-11 range and not 1-12 range as is default in c#? (the K format specifier from Java is what I need)

    ReplyDelete
    Replies
    1. I think there is no built-in format specifier in C#, equivalent to K format in Java. You might want to write a custom formatter ( ICustomFormatter ).

      Delete