Java中對數字格式的精度


你可以向以下格式說明符中新增一個精度說明符-

%f
%e
%g
%s

浮點數上的小數位數已知。

比如說我們聲明瞭一個格式化器物件 -

Formatter f1 = new Formatter();

現在,我們需要 3 位小數。為此,使用 1.3f -

f1.format("%1.3f", 29292929.98765432);

上面的程式碼將返回一個小數點後三位數 -

29292929.988

下面的程式碼是最終示例 -

示例

 即時演示

import java.util.Formatter;
public class Demo {
    public static void main(String args[]) {
       Formatter f1, f2, f3;
       f1 = new Formatter();
       f1.format("%1.3f", 29292929.98765432);
       System.out.println(f1);
       f2 = new Formatter();
       f2.format("%1.7f", 29292929.98765432);
       System.out.println(f2);
       f3 = new Formatter();
       f3.format("%1.9f", 29292929.98765432);
       System.out.println(f3);
    }
}

輸出

29292929.988
29292929.9876543
292929.987654320

更新於:2020 年 6 月 26 日

2K+ 次觀看

開啟您的 職業生涯

完成本課程後獲得認證

開始
廣告