c# ToString, 格式化字符串

(转自:http://hi.baidu.com/cyj380236628/blog/item/7303c52ee0479e5c4ec2263a.html)

格式化数值:有时,我们可能需要将数值以一定的格式来呈现,就需要对数值进行格式化。我们使用格式字符串指定格式。格式字符串采用以下形式:Axx,其中 A 为格式说明符,指定格式化类型,xx 为精度说明符,控制格式化输出的有效位数或小数位数。

格式说明符说明示例输出
C货币2.5.ToString("C")¥2.50
D十进制数25.ToString("D5")00025
E科学型25000.ToString("E")2.500000E+005
F固定点25.ToString("F2")25.00
G常规2.5.ToString("G")2.5
N数字2500000.ToString("N")2,500,000.00
X十六进制255.ToString("X")FF

formatCode 是可选的格式化代码字符串。(详细内容请搜索“格式化字符串”查看)

string.Format("{0:000}", 1)

显示格式是001

--取小数位前数字,不考虑四舍五入

select left('30000.72234', charindex('.', '30000.72234')-1)

--每三位用逗号相隔,留2位小数,不考虑四舍五入

select convert(varchar, cast(round(30000.72234,0) as money), 1)

--每三位用逗号相隔,不留小数位,考虑四舍五入

select left(convert(varchar, cast(round(30000.72234,0) as money), 1) , charindex('.', convert(varchar, cast(round(30000.72234,0) as money), 1))-1)

select ROUND(123.75633, 2),ROUND(123.75633, 2, 1)

必须用“{”和“}”将格式与其他字符分开。如果恰好在格式中也要使用大括号,可以用连续的两个大括号表示一个大括号,即: “{{”或者“}}”。

常用格式举例:

(1) int i=12345;

this.textBox1.Text=i.ToString();

//结果 12345(this指当前对象,或叫当前类的实例)

this.textBox2.Text=i.ToString("d8");

//结果 00012345

(2) int i=123;

double j=123.45;

string s1=string.Format("the value is {0,7:d}",i);

string s2=string.Format("the value is {0,7:f3}",j);

this.textBox1.Text=s1 ;

//结果 the value is 123

this.textBox2.Text=s2;

//结果 the value is 123.450

(3)double i=12345.6789;

this.textBox1.Text=i.ToString("f2"); //结果 12345.68

this.textBox2.Text=i.ToString("f6");

//结果 12345.678900

(4)double i=12345.6789;

this.textBox1.Text=i.ToString("n"); //结果 12,345.68

this.textBox2.Text=i.ToString(“n4”); //结果 12,345.6789

(5)double i=0.126;

string s=string.Format("the value is {0:p}",i);

this.textBox1.Text=i.ToString("p"); //结果 12.6%

this.textBox2.Text=s; //结果 the value is 12.6%

(6) DateTime dt =new DateTime(2003,5,25);

this.textBox1.Text=dt.ToString("yy.M.d");

//结果 03.5.25

this.textBox2.Text=dt.ToString(“yyyy年M月”);

//结果 2003年5月

Convert.ToDateTime("2005/12/22 22:22:22").ToString("yyyy/MM/dd HH:mm:ss")

"2005/12/22 22:22:22"

(7) int i=123;

double j=123.45;

string s=string.Format("i:{0,-7},j:{1,7}",i,j);

//-7表示左对齐,占7位

this.textBox1.Text=s ;

//结果i:123 ,j: 123.45