welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Friday, July 19, 2013

How to use String.format in .NET?

String.Format(“–{0,10}–”, “test”);–      test–
String.Format(“–{0,-10}–”, “test”);–test      –
Number formatting is culture dependant. For example, formatting a currency string on a system with regional settings to UK will return a result like £9.99, formatting a currency on a machine set for the US region would return $9.99.
specifiertypeformatoutput(double 1.2345)output(int -12345)
ddecimal(whole number){0:d}System.FormatException-12345
eexponent / scientific{0:e}1.234500e+000-1.234500e+004
ffixed point{0:f}1.23-12345.00
rround trippable{0:r}1.23System.FormatException

custom number formatting

specifiertypeformatoutput(double 1234.56)
0zero placeholder{0:00.000}1234.560
#digit placeholder{0:#.##}1234.56
.decimal point placeholder{0:0.0}1234.6
,thousand separator{0:0,0}1,235
In addition there is the group separator; this is useful for varying the format, depending on the value of the parameter passed. For example
String.Format("{0:£#,##0.00;(£#,##0.00);Nothing}", value);
This will output “£1,240.00″ if passed 1243.56.  It will output the same format bracketed if the value is negative “(£1,240.00)”, and will output the string “Nothing” if the number is zero.

date formatting

Date formats are very dependant on the culture information passed. The examples below are shown using the UK culture.
specifiertypeoutput(June 8, 1970 12:30:59)
dShort Date08/06/1970
DLong Date08 June 1970
tShort Time12:30
TLong Time12:30:59
fFull date and time08 June 1970 12:30
FFull date and time (long)08 June 1970 12:30:59
gDefault date and time08/06/1970 12:30
GDefault date and time (long)08/06/1970 12:30:59
MDay / Month8 June
rRFC1123 date stringMon, 08 Jun 1970 12:30:59 GMT
sSortable date/time1970-06-08T12:30:59
uUniversal time, local timezone1970-06-08 12:30:59Z
YMonth / YearJune 1970

custom date formatting

specifiertypeoutput(June 8, 1970 12:30:59)
dddShort Day NameMon
ddddFull Day NameMonday
hh2 digit hour12
HH2 digit hour (24 hour)12
mm2 digit minute30
MMMShort Month nameJun
MMMMMonth nameJune
yy2 digit year70
yyyy4 digit year1970
:seperator, e.g. {0:hh:mm:ss}12:30:59
/seperator, e.g. {0:dd/MM/yyyy}08/06/1970
There are others, including time zone formatting and so on, but the ones above are the most commonly used.


Post a Comment