使用 Formatter 在 Java 中垂直對齊數字值


如要垂直對齊 Java 中的數字值,請使用 Formatter。要使用 Formatter 類,請匯入以下包。

import java.util.Formatter;

採用一個數組 −

double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };

在顯示此雙陣列值時,使用 %f 設定空格 −

for (double d : arr) {
   f.format("%12.2f %12.2f %12.2f
", d, Math.ceil(d), Math.floor(d)); }

以上,我們還設定了小數位,即 12.2f 表示 2 個小數位。

以下是示例 −

示例

 即時演示

import java.util.Formatter;
public class Demo {
   public static void main(String[] argv) throws Exception {
      double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };
      Formatter f = new Formatter();
      f.format("%12s %12s %12s
", "Points1", "Points2", "Points3"); System.out.println("The point list...
"); for (double d : arr) { f.format("%12.2f %12.2f %12.2f
", d, Math.ceil(d), Math.floor(d)); } System.out.println(f); } }

輸出

The point list...
Points1  Points2  Points3
2.50     3.00     2.00
4.80     5.00     4.00
5.70     6.00     5.00
6.50     7.00     6.00
9.40     10.00    9.00
8.40     9.00     8.00
9.50     10.00    9.00
10.20    11.00    10.00
11.50    12.00    11.00

更新於: 30-07-2019

439 檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告