C# 中的格式化輸出


要在 C# 中設定格式化輸出,讓我們來看看格式化日期和 double 型別的示例。

設定 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

設定 DateTime 的格式化輸出

示例

即時演示

using System;
static class Demo {
   static void Main() {

      DateTime d = new DateTime(2018, 2, 8, 12, 7, 7, 123);
      Console.WriteLine(String.Format("{0:y yy yyy yyyy}", d));
      Console.WriteLine(String.Format("{0:M MM MMM MMMM}", d));
      Console.WriteLine(String.Format("{0:d dd ddd dddd}", d));
   }
}

輸出

18 18 2018 2018
2 02 Feb February
8 08 Thu Thursday

更新於:22-6-2020

1000+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.