Math.round()方法取整规则

刷题看到Math.round()题目,就知道又到了翻文档的时候了

返回最接近参数的 long。结果将舍入为整数:加上 1/2,对结果调用 floor 并将所得结果强制转换为 long 类型。换句话说,结果等于以下表达式的值:
(long)Math.floor(a + 0.5d)
特殊情况如下:
如果参数为 NaN,那么结果为 0。
如果结果为负无穷大或任何小于等于 Long.MIN_VALUE 的值,那么结果等于 Long.MIN_VALUE 的值。
如果参数为正无穷大或任何大于等于 Long.MAX_VALUE 的值,那么结果等于 Long.MAX_VALUE 的值。

下面直接贴例子

System.out.println("1.4 round结果" + Math.round(1.4));
System.out.println("1.5 round结果" + Math.round(1.5)); 
System.out.println("1.6 round结果" + Math.round(1.6));
System.out.println("2.4 round结果" + Math.round(2.4));
System.out.println("2.5 round结果" + Math.round(2.5));
System.out.println("2.6 round结果" + Math.round(2.6));
System.out.println("-1.4 round结果" + Math.round(-1.4));
System.out.println("-1.5 round结果" + Math.round(-1.5));
System.out.println("-1.6 round结果" + Math.round(-1.6));
System.out.println("-2.4 round结果" + Math.round(-2.4));
System.out.println("-2.5 round结果" + Math.round(-2.5));
System.out.println("-2.6 round结果" + Math.round(-2.6));

运行结果为

1.4 round结果1
1.5 round结果2
1.6 round结果2
2.4 round结果2
2.5 round结果3
2.6 round结果3
-1.4 round结果-1
-1.5 round结果-1
-1.6 round结果-2
-2.4 round结果-2
-2.5 round结果-2
-2.6 round结果-3

可以看出来,无论正数或者负数或者负数,运算规则相同,都是在给出数值的基础上+0.5,然后向下取整

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值