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);
      }
   }
}

在下面的示例中,讓我們格式化雙精度型別的字串。

示例

 線上演練

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

更新於:2020 年 6 月 22 日

454 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.