Java取整做法大全:Math.floor、Math.ceil、Math.rint和Math.round对比

作者:袖梨 2026-08-04

Java取整做法大全:Math.floor、Math.ceil、Math.rint和Math.round对比并不只看表面做法,关键还要理解相关条件、限制和后续影响。

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.5跟1和2都很接近,这时候就取偶数,如图。

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

Math.round(),这个round就有点意思了,如果只考虑正整数的情况下就很简单,就是我们平时说的四舍五入来算就行了,如果是负数,那么的话就要负数+0.5然后再向下取整,如Math.round(-0.6) = (-0.6+0.5)=-0.1,然后向下取整就是-1,

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

注意:

此种方法将会直接截取小数后面的部分,直接拿到整数。

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

Java取整方法大全: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));}}

总结

相关文章

精彩推荐