java的Math中三个取整方法ceil,floor,round

Math类中提供了三个与取整有关的方法:ceil,floor,round,这些方法的作用于它们的英文名称的含义相对应。

1.ceil:天花板,即向上取整,也就是数轴上的值向右取最近相邻整数。

     例如:Math.ceil(5.6) = 6;      Math.ceil(-11.6) = -11;

2.floor:地板,即向下取整,也就是数轴上的值向左取最近相邻整数。

      例如:Math.floor(5.6) = 5;     Math.floor(-11.6) = -12;

3.round:四舍五入。如果是正数,就很简单,如果是负数,那就需要分情况。

      其情况,包括小数部分是大于5,小于5,或者等于5.

      但是,这样记忆太繁琐,我们可以去看他的本质,

      很简单,jdk中定义了round函数的计算算法:round(x) = floor( x + 0.5) 无论正负

      所以。我们也就很容易计算,Math.round(-1.5) = -1;  Math.round(-1.4) = -1;  Math.round(-1.6) = -2

     通过对round算法的了解,我们也就知道了:四舍五入函数,比较特殊的是负数取整,小数部分为5的时候!

最后,附上jdk中对此的描述:

(1)public static long round(double a)  
returns the closest long to the argument. the result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. in other words, the result is equal to the value of the expression:    
    
  (long)math.floor(a  +  0.5d)  

猜你喜欢

转载自blog.csdn.net/romantic_jie/article/details/97534263