Math函数提供了四个取整方法:
Math.ceil( ):向上取整
Math.floor( ):向下取整
Math.round( ):四舍五入
Math.rint( ):四舍五入
Math.ceil( )方法:向上取整,即返回大于或等于参数的最小值double
例如,Math.ceil(11.3)返回12,Math.ceil(-11.3)返回-11。
Math.floor( )方法:向下取整,即返回小于或等于参数的最大值double
例如,Math.floor(11.3)返回11,Math.floor(-11.3)返回-12。
Math.rint( )方法:四舍五入,返回与double值最接近的double值,该值等于数学整数
例如,Math.rint(10.5)返回10.0,Math.rint(-10.5)返回-10.0,Math.rint(0.5)返回0.0,Math.rint(0.8)返回1.0。
注:在0.5时取偶数
Math.round( )方法:四舍五入,即返回最接近参数的整数
方法 | 描述 |
round( double) | 返回与参数值最接近的long,并将关系四舍五入为正无穷大 |
round( float) | 返回与参数值最接近的int,并将关系四舍五入为正无穷大 |
例如,Math.round(11.3)返回11,Math.round(11.6)返回12,Math.round(-11.3)返回-11,Math.round(-11.6)返回-12。
需要注意的是,这些方法都返回double类型的值,因此需要进行强制类型转换才能得到整数类型的结果。另外,这些方法都是静态方法,可以直接通过Math类调用。