English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将数字四舍五入到n个小数位

Java example大全

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

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

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

When running the program, the output is:

1.3457

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

这意味着,最多只能在点后打印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));
    }
}

When running the program, the output is:

1.346

In the above program, we use DecimalFormat class to round the given number num.

We use #, pattern declaration format #.###. This means that we want num to have at most3decimal places. We will also set the rounding mode to Ceiling, which will cause the last given position to be rounded up to the next number.

Therefore, the1.34567rounded to the decimal point after3digit will be printed1.346, the6The digit is the3decimal places5the next number.

Java example大全