Java 中的格式化輸出


  • String 提供格式化方法可以用於在 java 中列印格式化輸出。

  • System.out.printf() 方法可以用於在 java 中列印格式化輸出。

以下示例透過使用 format() 方法中的特定區域設定、格式和引數返回一個格式化的字串值

示例

import java.util.*;

public class StringFormat {
   public static void main(String[] args) {

      double e = Math.E;
      System.out.format("%f%n", e);
      System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
   }
}

輸出

上述程式碼示例將產生以下結果。

2.718282
2,7183

下面是格式化字串的另一個示例。

示例

public class HelloWorld {
   public static void main(String []args) {

      String name = "Hello World";
      String s1 = String.format("name %s", name);
      String s2 = String.format("value %f",32.33434);
      String s3 = String.format("value %32.12f",32.33434);
      System.out.print(s1);
      System.out.print("
");       System.out.print(s2);       System.out.print("
");       System.out.print(s3);       System.out.print("
");    } }

輸出

上述程式碼示例將產生以下結果。

name Hello World
value 32.334340
value 32.334340000000

更新日期:2020 年 6 月 21 日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.