Java中Math.ceil()、Math.floor()、Math.round()的区别

1、Math.ceil()

ceil表示“天花板”,向上取整;相当于水平数轴,向左取整

Math.ceil(2.6);     //3.0   ceil天花板 水平数轴向左取整
Math.ceil(-2.6);    //-2.0   ceil天花板 水平数轴向左取整

2、Math.floor()

floor表示“地板”,向下取整;相当于水平数轴,向右取整

Math.floor(2.6);    //2.0   floor地板 水平数轴向右取整
Math.floor(-2.6);   //-3.0   floor地板 水平数轴向右取整

3、Math.round()

round表示“四舍五入”,算法Math.floor(x+0.5)

Math.round(2.4);    //2     Math.floor(2.9)
Math.round(-2.4);   //-2    Math.floor(-1.9)
Math.round(2.5);    //3     Math.floor(3.0)
Math.round(-2.5);   //-2    Math.floor(-2.0)
Math.round(2.6);    //3     Math.floor(3.1)
Math.round(-2.6);   //-3    Math.floor(-2.1)

测试

public class MathDemo {
    public static void main(String[] args) {
        //  3   2   0   -2  -3  看成一条水平数轴的话,floor向右取整,ceil向左取整
        System.out.println(Math.ceil(2.6));     //3.0   ceil天花板 水平数轴向左取整
        System.out.println(Math.ceil(-2.6));     //-2.0   ceil天花板 水平数轴向左取整
        System.out.println(Math.floor(2.6));    //2.0   floor地板 水平数轴向右取整
        System.out.println(Math.floor(-2.6));    //-3.0   floor地板 水平数轴向右取整
        System.out.println("- - - - -");
        //  3   2   0   -2  -3  Math.floor(x+0.5)
        System.out.println(Math.round(2.4));    //2     Math.floor(2.9)
        System.out.println(Math.round(-2.4));   //-2    Math.floor(-1.9)
        System.out.println(Math.round(2.5));    //3     Math.floor(3.0)
        System.out.println(Math.round(-2.5));   //-2    Math.floor(-2.0)
        System.out.println(Math.round(2.6));    //3     Math.floor(3.1)
        System.out.println(Math.round(-2.6));   //-3    Math.floor(-2.1)
    }
}

结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值