原文: https://www.programiz.com/java-programming/examples/round-number-decimal

在此程序中,您将学习在 Java 中将给定数字四舍五入到小数点后 n 位。

示例 1:使用格式对数字取整

  1. public class Decimal {
  2. public static void main(String[] args) {
  3. double num = 1.34567;
  4. System.out.format("%.4f", num);
  5. }
  6. }

运行该程序时,输出为:

1.3457

在上面的程序中,我们使用format()方法将给定的浮点数num打印到小数点后 4 位。 小数点后 4 位格式为.4f.

这意味着,仅在之后打印最多 4 个位置(小数位),并且f表示打印浮点数。


示例 2:使用DecimalFormat取整数字

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);

        System.out.println(df.format(num));
    }
}

运行该程序时,输出为:

1.346

在上述程序中,我们使用DecimalFormat类将给定数字num舍入。

我们使用#模式#.###声明格式。 这意味着,我们希望num最多 3 个小数位。 我们还将舍入模式设置为Ceiling,这将导致最后一个给定的位置被舍入到下一个数字。

因此,将 1.34567 舍入到小数点后 3 位将打印 1.346,第 6 位是第 3 位小数点 5 的下一个数字。