Java中取整方法小结

Java中取整方法小结

Math类包括五个取整方法:

方法描述
ceil(x)x向上取整为它最接近的整数。该整数作为一个双精度值返回。
floor(x)x向下取整为它最接近的整数。该整数作为一个双精度值返回。
rint(x)x取整为它最接近的整数。如果x与两个整数的距离相等,偶数的整数作为一个双精度值返回。
round(x)如果x是单精度数,返回(int)Math.floor(x+0.5);如果x是双精度数,返回(long)Math.floor(x+0.5)。

ceil,floor,round,这些方法的作用于它们的英文名称的含义相对应,例如:

  • ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11
  • floor的英文是地板,该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12
  • rint方法取整为它最接近的整数。如果该值与两个整数的距离相等,偶数的整数作为一个双精度值返回,Math.rint(2.5)的结果是2,Math.rint(-2.5)的结果是-2,Math.rint(4.5)的结果是4
  • 最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.Math.round( )符合这样的规律:小数点后大于5全部加,等于5正数加,小于5全不加

测试代码如下:

package com.test4;

/**
 * 
 * @author Echo
 *
 */
public class Test {

    public static void main(String[] args) {
        System.out.println(Math.ceil(2.1));//3.0
        System.out.println(Math.ceil(2.0));//2.0
        System.out.println(Math.ceil(-2.0));//-2.0
        System.out.println(Math.ceil(-2.1));//-2.0

        System.out.println(Math.floor(2.1));//2.0
        System.out.println(Math.floor(2.0));//2.0
        System.out.println(Math.floor(-2.0));//-2.0
        System.out.println(Math.floor(-2.1));//-3.0

        System.out.println(Math.rint(2.1));//2.0
        System.out.println(Math.rint(-2.0));//-2.0
        System.out.println(Math.rint(-2.1));//-2.0
        System.out.println(Math.rint(2.5));//2.0
        System.out.println(Math.rint(4.5));//4.0
        System.out.println(Math.rint(-2.5));//-2.0

        System.out.println(Math.round(2.5));//3
        System.out.println(Math.round(2.5f));//3
        System.out.println(Math.round(-2.5));//-2

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值