Java的printf方法和format方法(格式化數位列印輸出)

2020-08-11 14:43:31

格式化數位列印輸出

  • 前面您看到使用print和println方法將字串列印到標準輸出(System.out)。
  • 由於所有數位都可以轉換爲字串(如本課程後面所述),因此您可以使用這些方法來列印出字串和數位的任意混合形式。
  • 但是,Java程式語言還有其他方法,允許您在包含數位時對列印輸出進行更多控制。
  • 格式化數位輸出操作是與數位操作相關的一種操作。主要涉及的方法是printf (),format()

printf 和format 方法

原文:
The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out. Thus, you can use format or printf anywhere in your code where you have previously been using print or println.
(解讀:之前熟悉的System.out是字元流物件,也就是說system.out是字元流物件的子類,所以作爲父類別字元流物件的方法printf and format都可以在System.out這個物件上呼叫)

//		之前的用法
		System.out.println("hello");
		System.out.print("sayhi");
		
//		補充的格式化輸出用法
		System.out.format("", args);
		System.out.printf("jiji");

這兩個java.io.PrintStream字元流的方法(format,printf)的語法相同:

public PrintStream format(String format, Object... args)

其中format是一個字串,用於指定要使用的格式,而args是使用該格式要列印的變數的列表。 一個簡單的例子是:

System.out.format("The value of " + "the float variable is " +
     "%f, while the value of the " + "integer variable is %d, " +
     "and the string is %s", floatVar, intVar, stringVar); 

總結:printf 和format方法會用,瞭解即可。後面還有一個國際化的語言環境設定瞭解即可。

The DecimalFormat Class

這個類可以自定義設定數位的格式,比較方便。瞭解介面,即查即用。