C# 中的格式化字串文字
要格式化 C# 中的字串文字,請使用 String.Format 方法。
在下例中,0 是要將字串值插入特定位置的物件的索引 −
using System; namespace Demo { class Test { static void Main(string[] args) { decimal A = 15.2 m; string res = String.Format("Temperature = {0}°C.", A); Console.WriteLine(res); } } }
在下例中,我們為 double 型別格式化字串。
示例
using System; class Demo { public static void Main(String[] args) { Console.WriteLine("Three decimal places..."); Console.WriteLine( String.Format("{0:0.000}", 987.383)); Console.WriteLine( String.Format("{0:0.000}", 987.38)); Console.WriteLine(String.Format("{0:0.000}", 987.7899)); Console.WriteLine("Thousands Separator..."); Console.WriteLine(String.Format("{0:0,0.0}", 54567.46)); Console.WriteLine(String.Format("{0:0,0}", 54567.46)); } }
輸出
Three decimal places... 987.383 987.380 987.790 Thousands Separator... 54,567.5 54,567
廣告