平時我們使用的是Console類提供的格式化數據輸出方法。那麼,C#中有沒有別的方法可以使用呢?答案是肯定的,用String類的格式化方法也可以有同樣的功能。String類提供了很強大的Format()方法用以格式化字符串,它的語法和WriteLine()類似。
Format()的語法如下:
string str=string.Format("格式化字符串",參數列表);
舉個簡單的例子:
string str=string.Format("{0}+{1}={2}",1,2,1+2);
Console.WriteLine(str);
輸出結果:
1+2=3
其中,”{0}+{1}={2}“就是格式字符串,{0},{1},{2}為占位符。
除了上面的用法之外,string.Format()方法還有格式化數值的功能,具體用法如表所示:
格式化數值 字符 說明 示例 輸出
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}",25000) 25,000.00
X 十六進制 string.Format("{0:X000}",12) C
P 百分比 string.Format("{0:P}",12.34) 1234.00%
舉例說明:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormatTest
{
class Program
{
static void Main(string[] args)
{
string str = string.Empty;
Console.WriteLine("標准數字化格式");
str = string.Format(
"(C)Currency:{0:C}\n"+
"(D)Decimal:{0:D}\n" +
"(G)General:{1:G}\n" +
"(p)Percent:{1:P}\n" +
"(X)Hexadecimal:{0:X}\n" ,
-12345,-123.4567f);
Console.WriteLine(str);
Console.ReadLine();
}
}
}