Math.round(),Math.ceil(),Math.floor()介绍

Math类中提供了三个与取整有关的方法:ceil(),floor(),round()

首先看一下Math类的部分源码


我们可以知道,ceil()和floor()返回的都是double类型;round()返回的是int 和 long 类型。
这些方法的作用于它们的英文名称的含义相对应

1、ceil()

ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.2)的结果为12.0,Math.ceil(-11.2)的结果为-11.0;

    @Test
    public void ceil(){
        System.out.println(Math.ceil(11.2));   //12.0
        System.out.println(Math.ceil(-11.2));   //-11.0
    }
2、floor()

floor的英文是地板,该方法就表示向下取整,Math.floor(11.2)的结果是11.0,Math.floor(-11.2)的结果-12.0;

    @Test
    public void floor(){
        System.out.println(Math.floor(11.2));  //11.0
        System.out.println(Math.floor(-11.2));   //-12.0
    }
3、ceil()

最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.2)的结果是11,Math.round(-11.2)的结果为-11,Math.round(-11.6)的结果为-12,

   @Test
   public void round(){
       System.out.println(Math.round(11.2));  //11
       System.out.println(Math.round(-11.2));   //-11
       System.out.println(Math.round(-11.6));   //-12
   }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值