-
向下取整
Math.floor()
,向下取整就是取最小的整数,返回的总是小于等于原数。 -
向上取整
Math.ceil()
,向上取整顾名思义就是取最大的整数,返回的总是大于等于原数。 -
接近取整
Math.rint()
,接近取整顾名思义就是接近哪个取整哪个。
如1.6接近2,所以就取2;1.4接近1,所以就取1;那么1.5呢,1.5跟1和2都很接近,这时候就取偶数。 -
四舍五入或(+0.5向下取整)
Math.round()
,如果只考虑正整数的情况下就很简单,就是我们平时说的四舍五入来算就行了;如果是负数,那么的话就要负数+0.5然后再向下取整,如Math.round(-0.6) = (-0.6+0.5)=-0.1,然后向下取整就是-1, -
类型强转(int)double,(int) float…
注意:此种方法将会直接截取小数后面的部分,直接拿到整数。
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));
}
- 结果:
1.0
-2.0
--------
2.0
-1.0
--------
2.0
1.0
2.0
2.0
--------
3
-2
1