Console.WriteLine()函數中{}輸出格式詳解(C#)

其中格式項都採用以下形式:git

{index[,alignment][:formatString]}   spa

 

其中"index"指索引佔位符,這個確定都知道;orm

",alignment"按字面意思顯然是對齊方式,以","爲標記;索引

":formatString"就是對輸出格式的限定,以":"爲標記。ip

 

alignment:可選,是一個帶符號的整數,指示首選的格式化字段寬度。若是「對齊」值小於格式化字符串的長度,「對齊」會被忽略,而且使用格式化字符串的長度做爲字段寬度。若是「對齊」爲正數,字段的格式化數據爲右對齊;若是「對齊」爲負數,字段的格式化數據爲左對齊。若是須要填充,則使用空白。若是指定「對齊」,就須要使用逗號。ci

 

formatString:由標準或自定義格式說明符組成。字符串

字符string

說明it

示例io

輸出

C          貨幣 string.Format("{0:C3}", 2) $2.000
D        十進制 string.Format("{0:D3}", 2) 002
E     科學計數法 1.20E+001 1.20E+001
G         常規 string.Format("{0:G}", 2) 2
N  用分號隔開的數字 string.Format("{0:N}", 250000) 250,000.00
X       十六進制 string.Format("{0:X000}", 12) C
    string.Format("{0:000.000}", 12.2) 012.200



Specifier Type Format Output 
(Passed 
Double 1.42)
Output 
(Passed 
Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.
FormatException
-12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.
FormatException
x Hexadecimal {0:x4} System.
FormatException
cf90

 

Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002

 

Specifier Type Example Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, ... Second fractions {0:fff} 932
gg, ... Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002
相關文章
相關標籤/搜索