您的位置:首页 >Java取整方法大全:Math.floor、Math.ceil、Math.rint和Math.round对比
发布于2026-08-05 阅读(0)
扫一扫,手机访问
Math.floor(),向下取整就是取最小的整数。比如 1.9 得到 1.0,-1.9 得到 -2.0 —— 结果总是小于等于原始数值。一句话:往负无穷方向走。
Math.ceil(),向上取整则正好相反,取最大的整数。1.9 返回 2.0,-1.9 返回 -1.0,结果总是大于等于原始数值。说白了就是往正无穷方向舍入。
Math.rint(),顾名思义,离哪个整数近就取哪个。1.6 接近 2,取 2;1.4 接近 1,取 1。那 1.5 呢?它和 1、2 一样近,这时候规则是取偶数,所以 1.5 取 2,2.5 也取 2(因为 2 是偶数)。
Math.round() 这个就有点意思了。如果只考虑正整数,直接按我们平时说的四舍五入理解就行。但遇到负数,规则其实是:先给数值加上 0.5,再向下取整。比如 Math.round(-0.6),先算 -0.6 + 0.5 = -0.1,然后向下取整得到 -1。所以负数的四舍五入和直觉不太一样,务必留意。
注意:这种方法会直接截断小数部分,只保留整数部分。不做任何舍入,纯粹是“砍掉”小数点后面的内容。


public class demo_2 {
public static void main(String[] args) {
// 向下取整
System.out.println(Math.floor(1.9));
System.out.println(Math.floor(-1.9));
System.out.println("--------");
// 向上取整
System.out.println(Math.ceil(1.9));
System.out.println(Math.ceil(-1.9));
System.out.println("--------");
// 接近取整
System.out.println(Math.rint(1.6));
System.out.println(Math.rint(1.4));
System.out.println(Math.rint(1.5));
System.out.println(Math.rint(2.5));
System.out.println("--------");
// 四舍五入
System.out.println(Math.round(2.5));
System.out.println(Math.round(-2.5));
System.out.println(Math.round(1.2));
}
}
五种取整方式各有各的用途:向下、向上、接近取整、四舍五入(带负数的特殊规则),以及直接强转截断。实际开发中,根据场景选择合适的方法,能避免很多隐蔽的 bug。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8