Java取整函数的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pan_junbiao/article/details/84943301

在开发中,取整操作使用是很普遍的,所以Java在Math类中添加了数字取整方法。在Math类中主要包括以下几种取整方法。

public static double ceil(double a):返回大于等于参数的最小整数。

public static double floor(double a):返回小于等于参数的最大整数。

public static double rint(double a):返回与参数最接近的整数,如果两个同为整数且同样接近,则结果取偶数。

public static int round(float a):将参数加上0.5后返回与参数最近的整数。

public static long round(double a):将参数加上0.5后返回与参数最近的整数,然后强制转换为长整型。

下面举例说明Math类中取整方法的使用。

public static void main(String args[])
{
	// 返回第一个大于等于参数的整数
	System.out.println("使用ceil()方法取整:" + Math.ceil(5.2));

	// 返回第一个小于等于参数的整数
	System.out.println("使用floor()方法取整:" + Math.floor(2.5));

	// 返回与参数最接近的整数
	System.out.println("使用rint()方法取整:" + Math.rint(2.7));

	// 返回与参数最接近的整数
	System.out.println("使用rint()方法取整:" + Math.rint(2.5));

	// 将参数加上0.5后返回最接近的整数
	System.out.println("使用round()方法取整:" + Math.round(3.4f));

	// 将参数加上0.5后返回最接近的整数,并将结果强制转换为长整型
	System.out.println("使用round()方法取整:" + Math.round(2.5));
}

执行结果:

使用ceil()方法取整:6.0
使用floor()方法取整:2.0
使用rint()方法取整:3.0
使用rint()方法取整:2.0
使用round()方法取整:3
使用round()方法取整:3

猜你喜欢

转载自blog.csdn.net/pan_junbiao/article/details/84943301