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)  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值