Math 的 floor,round 和 ceil 方法比较

344 阅读1分钟
一、定义

 1 ceil() “天花板”,向上取最接近的整数。 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。

 2 floor() “地板”,向下取最接近的整数。 返回小于等于(<=)给定参数的最大整数 。

 3 rint() 返回与参数最接近的整数。返回类型为double。注:如果上下都接近,取偶数。

 4 round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。

二、示例

Math.floor(1.4)=1.0 

Math.floor(1.5)=1.0 

Math.floor(1.6)=1.0 

Math.floor(-1.4)=-2.0 

Math.floor(-1.5)=-2.0 

Math.floor(-1.6)=-2.0 


Math.round(1.4)=1 

Math.round(1.5)=2 

Math.round(1.6)=2 

Math.round(-1.4)=-1 

Math.round(-1.5)=-1 

Math.round(-1.6)=-2(!!) 


 Math.ceil(1.4)=2.0 

Math.ceil(1.5)=2.0 

Math.ceil(1.6)=2.0 

Math.ceil(-1.4)=-1.0 

Math.ceil(-1.5)=-1.0 

Math.ceil(-1.6)=-1.0 


 Math.rint(1.4)=1.0 

Math.rint(1.5)=2.0(!!) 

Math.rint(1.6)=2.0 

Math.rint(-1.4)=-1.0 

Math.rint(-1.5)=-2.0(!!) 

Math.rint(-1.6)=-2.0 

———————————————— 

 原文链接:https://blog.csdn.net/bd_fuhong/article/details/90046754