Java中Math类的几个四舍五入方法的区别

时间:2023-07-28 17:38:20

JAVA取整以及四舍五入

下面来介绍将小数值舍入为整数的几个方法:Math.ceil()、Math.floor()和Math.round()。 这三个方法分别遵循下列舍入规则:
Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;

Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。

下面来看几个例子:

Math.ceil(25.9) //

Math.ceil(25.5) //

Math.ceil(25.1) //

Math.ceil(25.0)
// Math.round(25.9) // Math.round(25.5) // Math.round(25.1) // Math.floor(25.9) // Math.floor(25.5) // Math.floor(25.1) //
import java.math.BigDecimal; //引入这个包

public class Test {
public static void main(String[] args) { double i = 3.856; // 舍掉小数取整
System.out.println("舍掉小数取整:Math.floor(3.856)=" + (int) Math.floor(i)); // 四舍五入取整
System.out.println("四舍五入取整:(3.856)="
+ new BigDecimal(i).setScale(0, BigDecimal.ROUND_HALF_UP)); // 四舍五入保留两位小数
System.out.println("四舍五入取整:(3.856)="
+ new BigDecimal(i).setScale(2, BigDecimal.ROUND_HALF_UP)); // 凑整,取上限
System.out.println("凑整:Math.ceil(3.856)=" + (int) Math.ceil(i)); // 舍掉小数取整
System.out.println("舍掉小数取整:Math.floor(-3.856)=" + (int) Math.floor(-i));
// 四舍五入取整
System.out.println("四舍五入取整:(-3.856)="
+ new BigDecimal(-i).setScale(0, BigDecimal.ROUND_HALF_UP)); // 四舍五入保留两位小数
System.out.println("四舍五入取整:(-3.856)="
+ new BigDecimal(-i).setScale(2, BigDecimal.ROUND_HALF_UP)); // 凑整,取上限
System.out.println("凑整(-3.856)=" + (int) Math.ceil(-i));
} }