JAVA中取整数的四种方法

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......

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

 

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));
	}
}

猜你喜欢

转载自blog.csdn.net/qq_63802547/article/details/127818807
今日推荐