您的位置:首页 > 移动开发 > Objective-C

C#:String.Format 方法 (String, Object)的用法

2010-02-08 08:56 633 查看
MSDN定义

将指定的String中的格式项替换为指定的Object实例的值的文本等效项。

format 参数由零或多个文本序列与零或多个索引占位符混合组成,其中索引占位符称为格式项,对应于与此方法的参数

列表中的对象。格式设置过程将每个格式项替换为相应对象值的文本表示形式。格式项的语法是 {索引[,对齐方式][:格式字符串]},它指定了一个强制索引、格式化文本的可选长度和对齐方式,以及格式说明符字符的可选字符串,其中格式说明符字符用于控制如何设置相应对象的值的格式。格式项的组成部分包括:

索引
从零开始的整数,指示对象列表中要格式化的元素。如果由索引指定的对象为 null 引用(在 Visual Basic 中为 Nothing),则格式项将被空字符串 ("") 替换。

对齐方式
可选整数,指示包含格式化值的区域的最小宽度。如果格式化值的长度小于对齐方式,则用空格填充该区域。如果对齐方式为负,则格式化值将在该区域中左对齐;如果对齐方式为正,则格式化值将右对齐。如果没有指定对齐方式,则该区域的长度为格式化值的长度。如果指定对齐方式,则需要使用逗号。

格式字符串
可选的格式说明符字符串。如果没有指定格式字符串,并且对应的参数实现了IFormattable接口,则将 null 引用(在 Visual Basic 中为 Nothing) 用作IFormattable.ToString格式字符串。因此,IFormattable.ToString 的所有实现都必须允许 null 引用(在 Visual Basic 中为 Nothing) 作为格式字符串,并以String对象的形式返回对象表示形式的默认格式设置。如果指定格式字符串,则需要使用冒号。

必须使用前导大括号字符和尾部大括号字符,即“{”和“}”。若要在 format 中指定单个大括号字符,请指定两个前导大括号字符或尾部大括号字符;即“{{”或“}}”。

String.Format的多格式定义:
这里所谓的多格式是指一个格式项中可以定义1~3个格式参数,每种格式参数用分号(;)隔开。带2个和3个格式参数的格式项所对应的值必须是数值类型的,这样才能判断是否为负数、正数、零。
带1个格式参数:



//以科学计数法的格式输出
double p1 = 1000000;
Response.Write(String.Format("{0:E2}", p1));




带2个格式参数:

/*当格式项对应的值为非负数,则选择第一种格式;值为负数则选第二种格式*/
double p1 = 10000;
double p2 = -2420.50;
Response.Write(String.Format("{0:#,###0.00;#,###0.000;}<BR>", p1));
Response.Write(String.Format("{0:#,###0.00;#,###0.000;}", p2));


带3个格式参数:

/*当格式项对应的值为正数则选择第一张格式;
负数则为第二中格式;
值等于零则为第三种格式*/
1double p1 = 10000;
double p2 = -2420.50;
double p3 = 0.00;
Response.Write(String.Format("{0:#,###0.00;#,###0.000;#,###0.0000}<BR>", p1));
Response.Write(String.Format("{0:#,###0.00;#,###0.000;#,###0.0000}<BR>", p3));
Response.Write(String.Format("{0:#,###0.00;#,###0.000;#,###0.0000}", p2));




C#格式化数值结果表
字符
说明
示例
输出

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

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 zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates
Note that date formatting is especially dependant on the system's regional settings; the example strings here are from my local locale.

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

The 'U' specifier seems broken; that string certainly isn't sortable.

Custom date formatting:

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

Enumerations
Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/viclm/archive/2009/04/29/4136323.aspx





示例



int a = 12345678;
//格式为sring输出
// Label1.Text = string.Format("asdfadsf{0}adsfasdf",a);
// Label2.Text = "asdfadsf"+a.ToString()+"adsfasdf";
// Label1.Text = string.Format("asdfadsf{0:C}adsfasdf",a);//asdfadsf¥1,234.00adsfasdf
// Label2.Text = "asdfadsf"+a.ToString("C")+"adsfasdf";//asdfadsf¥1,234.00adsfasdf

double b = 1234.12543;
a = 12345678;
//格式为特殊的string样式输出
// Label1.Text = string.Format("asdfadsf{0:C}adsfasdf",b);//asdfadsf¥1,234.13adsfasdf
// Label2.Text = "asdfadsf"+b.ToString("C")+"adsfasdf";//asdfadsf¥1,234.13adsfasdf
// Label1.Text = string.Format("{0:C3}",b);//¥1,234.125
// Label2.Text = b.ToString("C3");//¥1,234.125
// Label1.Text = string.Format("{0:d}",a);//十进制--12345678
// Label2.Text = b.ToString("d");//十进制--相同的类型,转换报错
// Label1.Text = string.Format("{0:e}",a);//指数--1.234568e+007
// Label2.Text = b.ToString("e");//指数--1.234125e+003

// Label1.Text = string.Format("{0:f}",a);//定点数--12345678.00
// Label2.Text = b.ToString("f");//定点数--1234.13
// Label1.Text = string.Format("{0:n}",a);//数值--12,345,678.00
// Label2.Text = b.ToString("n");//数值--1,234.13
// Label1.Text = string.Format("{0:x}",a);//十六进制--bc614e
// Label2.Text = b.ToString("x");//16--带有小数不能转换,出错
// Label1.Text = string.Format("{0:g}",a);//通用为最紧凑--12345678
// Label2.Text = b.ToString("g");//通用为最紧凑--1234.12543
// Label1.Text = string.Format("{0:r}",a);//转来转去不损失精度--整数不允许用,报错
// Label2.Text = b.ToString("r");//转来转去不损失精度--1234.12543

b = 4321.12543;
a = 1234;
//自定义模式输出:
// 0 描述:占位符,如果可能,填充位
// Label1.Text = string.Format("{0:000000}",a);// 001234
// Label2.Text = string.Format("{0:000000}",b);// 004321
// # 描述:占位符,如果可能,填充位
// Label1.Text = string.Format("{0:#######}",a);// 1234
// Label2.Text = string.Format("{0:#######}",b);// 4321
// Label1.Text = string.Format("{0:#0####}",a);// 01234
// Label2.Text = string.Format("{0:0#0000}",b);// 004321

// . 描述:小数点
// Label1.Text = string.Format("{0:000.000}",a);//1234.000
// Label2.Text = string.Format("{0:000.000}",b);//4321.125
b = 87654321.12543;
a = 12345678;
// , 描述:数字分组,也用于增倍器
// Label1.Text = string.Format("{0:0,00}",a);// 12,345,678
// Label2.Text = string.Format("{0:0,00}",b);// 87,654,32
// Label1.Text = string.Format("{0:0,}",a);// 12346
// Label2.Text = string.Format("{0:0,}",b);// 87654
// Label1.Text = string.Format("{0:0,,}",a);// 12
// Label2.Text = string.Format("{0:0,,}",b);// 88
// Label1.Text = string.Format("{0:0,,,}",a);// 0
// Label2.Text = string.Format("{0:0,,,}",b);// 0
// % 描述:格式为百分数
// Label1.Text = string.Format("{0:0%}",a);// 1234567800%
// Label2.Text = string.Format("{0:#%}",b);// 8765432113%
// Label1.Text = string.Format("{0:0.00%}",a);// 1234567800.00%
// Label2.Text = string.Format("{0:#.00%}",b);// 8765432112.54%
// 'abc' 描述:显示单引号内的文本
// Label1.Text = string.Format("{0:'文本'0}",a);// 文本12345678
// Label2.Text = string.Format("{0:文本0}",b);// 文本87654321
// / 描述:后跟1要打印字的字符,也用于转移符/n等
// Label1.Text = string.Format("/"你好!/"");// "你好!"
// Label2.Text = string.Format("//c//books//new//we.asp");///c/books/new/we.asp
// @描述:后跟要打印字的字符,
// Label1.Text = string.Format(@"""你好!"""); // "你好!"要打印"则需要输入两对才可以
// Label2.Text = string.Format(@"/c/books/new/we.asp");///c/books/new/we.asp
格式 原始数据 结 果
"{0:P}" 0.40 40%
数字 {0:N2} 12.36
数字 {0:N0} 13
货币 {0:c2} $12.36
货币 {0:c4} $12.3656
货币 "¥{0:N2}" ¥12.36
科学计数法 {0:E3} 1.23E+001
百分数 {0:P} 12.25% P and p present the same.
日期 {0:D} 2006年11月25日
日期 {0:d} 2006-11-25
日期 {0:f} 2006年11月25日 10:30
日期 {0:F} 2006年11月25日 10:30:00
日期 {0:s} 2006-11-26 10:30:00
时间 {0:T} 10:30:00

DateTime dt = DateTime.Now;
Label1.Text = dt.ToString();//2005-11-5 13:21:25
Label2.Text = dt.ToFileTime().ToString();//127756416859912816
Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
Label7.Text = dt.ToOADate().ToString();//38661.5565508218
Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
Label9.Text = dt.ToShortTimeString().ToString();//13:21
Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25

Label1.Text = dt.Year.ToString();//2005
Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
Label3.Text = dt.DayOfWeek.ToString();//Saturday
Label4.Text = dt.DayOfYear.ToString();//309
Label5.Text = dt.Hour.ToString();//13
Label6.Text = dt.Millisecond.ToString();//441
Label7.Text = dt.Minute.ToString();//30
Label8.Text = dt.Month.ToString();//11
Label9.Text = dt.Second.ToString();//28
Label10.Text = dt.Ticks.ToString();//632667942284412864
Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864

Label1.Text = dt.ToString();//2005-11-5 13:47:04
Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
Label10.Text = dt.CompareTo(dt).ToString();//0
Label11.Text = dt.Add(?).ToString();//问号为一个时间段

Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
Label2.Text = dt.Equals(dt).ToString();//True
Label3.Text = dt.GetHashCode().ToString();//1474088234
Label4.Text = dt.GetType().ToString();//System.DateTime
Label5.Text = dt.GetTypeCode().ToString();//DateTime

Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT

Label1.Text = string.Format("{0:d}",dt);//2005-11-5
Label2.Text = string.Format("{0:D}",dt);//2005年11月5日
Label3.Text = string.Format("{0:f}",dt);//2005年11月5日 14:23
Label4.Text = string.Format("{0:F}",dt);//2005年11月5日 14:23:23
Label5.Text = string.Format("{0:g}",dt);//2005-11-5 14:23
Label6.Text = string.Format("{0:G}",dt);//2005-11-5 14:23:23
Label7.Text = string.Format("{0:M}",dt);//11月5日
Label8.Text = string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
Label9.Text = string.Format("{0:s}",dt);//2005-11-05T14:23:23
Label10.Text string.Format("{0:t}",dt);//14:23
Label11.Text = string.Format("{0:T}",dt);//14:23:23
Label12.Text = string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
Label13.Text = string.Format("{0:U}",dt);//2005年11月5日 6:23:23
Label14.Text = string.Format("{0:Y}",dt);//2005年11月
Label15.Text = string.Format("{0}",dt);//2005-11-5 14:23:23
Label16.Text = string.Format("{0:yyyyMMddHHmmssffff}",dt);
stringstr1 =string.Format("{0:N1}",56789); //result: 56,789.0
stringstr2 =string.Format("{0:N2}",56789); //result: 56,789.00
stringstr3 =string.Format("{0:N3}",56789); //result: 56,789.000
stringstr8 =string.Format("{0:F1}",56789); //result: 56789.0
stringstr9 =string.Format("{0:F2}",56789); //result: 56789.00
stringstr11 =(56789 / 100.0).ToString("#.##"); //result: 567.89
stringstr12 =(56789 / 100).ToString("#.##"); //result: 567

C 或 c
货币
Console.Write("{0:C}", 2.5); //$2.50
Console.Write("{0:C}", -2.5); //($2.50)

D 或 d
十进制数
Console.Write("{0:D5}", 25); //00025

E 或 e
科学型
Console.Write("{0:E}", 250000); //2.500000E+005

F 或 f
固定点
Console.Write("{0:F2}", 25); //25.00
Console.Write("{0:F0}", 25); //25

G 或 g
常规
Console.Write("{0:G}", 2.5); //2.5

N 或 n
数字
Console.Write("{0:N}", 2500000); //2,500,000.00

X 或 x
十六进制
Console.Write("{0:X}", 250); //FA
Console.Write("{0:X}", 0xffff); //FFFF

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/viclm/archive/2009/04/29/4136323.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: