位置:首页 > Java > Java取整方法详解:floor、ceil、rint与round对比

Java取整方法详解:floor、ceil、rint与round对比

时间:2026-08-20  |  作者:游戏探长  |  阅读:0

1.向下取整

Math.floor() 表示向下取整,也就是取最小的整数。

比如 1.9 得到 1.0,-1.9 得到 -2.0。结果总是小于等于原始数值,也就是往负无穷方向走。

2.向上取整

Math.ceil() 表示向上取整,和向下取整正好相反,取最大的整数。

1.9 返回 2.0,-1.9 返回 -1.0。结果总是大于等于原始数值,也就是往正无穷方向舍入。

3.接近取整

Math.rint() 的规则是:离哪个整数近,就取哪个。

  • 1.6 接近 2,取 2
  • 1.4 接近 1,取 1

如果刚好处在中间,比如 1.5,那么它和 1、2 一样近。这时规则是取偶数

  • 1.5 取 2
  • 2.5 也取 2,因为 2 是偶数

4.四舍五入(或 +0.5 后向下取整)

Math.round() 如果只看正数,可以直接按平时理解的四舍五入来记。

但遇到负数时,规则其实是:先给数值加上 0.5,再向下取整

比如 Math.round(-0.6),先算 -0.6 + 0.5 = -0.1,然后向下取整得到 -1。

所以,负数的四舍五入和直觉不太一样,务必留意。

5.类型强转 (int)double, (int)float...

注意:这种方法会直接截断小数部分,只保留整数部分。

它不做任何舍入,纯粹是“砍掉”小数点后面的内容。

Ja va取整方法大全:Math.floor、Math.ceil、Math.rint和Math.round对比

Ja va取整方法大全:Math.floor、Math.ceil、Math.rint和Math.round对比

示例代码

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。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多