⑴ToString的格式说明符
C#中的每个对象都继承ToString方法,此方法返回该对象的字符串表示形式。例如,所有int类型的变量都有一个ToString方法,从而允许将变量的内容作为字符串返回。
下面用格式说明符返回int类型对象的十进制和十六进制字符串。
int x = 12;
Console.WriteLine("十进制:\tx = {0}", x.ToString());
Console.WriteLine("十六进制:\tx = {0}", x.ToString("x"));
Console.WriteLine("十六进制:\tx = {0}", x.ToString("X"));
Console.WriteLine("十六进制(二位):x = {0}", x.ToString("X2"));
int y = 2623;
Console.WriteLine("十六进制(四位):y = {0}", y.ToString("X4"));
输出:
十进制: x = 12
十六进制: x = c
十六进制: x = C
十六进制(二位): x = 0C
十六进制(四位): y = 0A3F
⑵复合格式化
.NET Framework 的复合格式化功能受到诸如String.Format方法和System.Console以及System.IO.TextWriter的输出方法的支持,该功能可以将嵌入源字符串中的每个索引格式项替换为值列表中对应元素的格式化等效项。
string myFName = "Fred";
string myLName = "Opals";
int myInt = 100;
//{0,10}格式指明占有10格且右对齐
string FormatFName = String.Format("First Name = |{0,10}|", myFName);
string FormatLName = String.Format("Last Name = |{0,10}|", myLName);
string FormatPrice = String.Format("Price = |{0,10:C}|", myInt);
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);
//{0,-10}占有10格左对齐
FormatFName = String.Format("First Name = |{0,-10}|", myFName);
FormatLName = String.Format("Last Name = |{0,-10}|", myLName);
FormatPrice = String.Format("Price = |{0,-10:C}|", myInt);
Console.WriteLine(FormatFName);
Console.WriteLine(FormatLName);
Console.WriteLine(FormatPrice);
输出:
First Name = | Fred|
Last Name = | Opals|
Price = | ¥100.00|
First Name = |Fred |
Last Name = |Opals |
Price = |¥100.00 |
数字格式的分隔符是冒号“:”,冒号右边的第1个字符是格式说明符,后接精度说明。如果没有精度说明表示精度为2。
double pi = 3.14159265;
Console.WriteLine("{0:c}", pi); //¥3.14
Console.WriteLine("{0:c4}", pi); //¥3.1416
Console.WriteLine("{0:e}", pi); //3.141593e+000
Console.WriteLine("{0:e3}", pi); //3.142e+000
Console.WriteLine("{0:f}", pi); //3.14
Console.WriteLine("{0:f6}", pi); //3.141593
Console.WriteLine("{0:g}", pi); //3.14159265
Console.WriteLine("{0:p}", pi); //314.16%
int i = 12345;
Console.WriteLine("{0:d}", i); //12345
Console.WriteLine("{0:d8}", i); //00012345
Console.WriteLine("{0:x}", i); //3039
double ni = 123456789;
Console.WriteLine("\n{0:n}", ni); //123,456,789.00
转载于:https://www.cnblogs.com/xpycy/archive/2012/11/10/2764377.html