C#中的字符串格式化

作者在 2006-08-24 18:49:00 发布以下内容

Strings

There really isn't any formatting within a strong, beyond it's alignment. Alignment works for any argument being printed in a String.Format call.

Sample Generates
String.Format("->{1,10}<-", "Hello"); -> Hello<-
String.Format("->{1,-10}<-", "Hello"); ->Hello <-

Numbers

Basic number formatting specifiers:

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

Custom number formatting:

Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two
C# | 阅读 1003 次
文章评论,共0条
游客请输入验证码