JAVA中取整数的4种方法总结

 更新时间:2023年07月25日 09:33:57   作者:飞得更高100  
这篇文章主要给大家介绍了关于JAVA中取整数的4种方法,在java的Math类中,提供了许许多多的和数学计算有关的方法,其中也包括取整的,需要的朋友可以参考下

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

总结

到此这篇关于JAVA中取整数的4种方法的文章就介绍到这了,更多相关JAVA取整数方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论