Tostring()

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: 567this

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

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); //FFFF3d

formatCode 是可選的格式化代碼字符串。(詳細內容請搜索「格式化字符串」查看)orm

 

必須用「{」和「}」將格式與其餘字符分開。若是剛好在格式中也要使用大括號,能夠用連續的兩個大括號表示一個大括號,即: 「{{」或者「}}」。對象

經常使用格式舉例:blog

(1) int i=12345;字符串

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

//結果 12345(this指當前對象,或叫當前類的實例)it

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

//結果 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

相關文章
相關標籤/搜索