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,然后向下取整

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章