public class MathTest {
public static void main(String[] args) {
System.out.println("小数点后第一位=5");
System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));
System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));
System.out.println();
System.out.println("小数点后第一位<5");
System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));
System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));
System.out.println();
System.out.println("小数点后第一位>5");
System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));
System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));
}
}
运行结果:
1、小数点后第一位=5
2、正数:Math.round(11.5)=12
3、负数:Math.round(-11.5)=-11
4、
5、小数点后第一位<5
6、正数:Math.round(11.46)=11
7、负数:Math.round(-11.46)=-11
8、
9、小数点后第一位>5
10、正数:Math.round(11.68)=12
11、负数:Math.round(-11.68)=-12
根据上面例子的运行结果,我们还可以按照如下方式总结,或许更加容易记忆:
1、参数的小数点后第一位<5,运算结果为参数整数部分。
2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。
终结:大于五全部加,等于五正数加,小于五全不加。
转载自:http://blog.sina.com.cn/s/blog_4b06743c0100lst3.html
-----------------------------------------------------------------------------
以上是原来的分析~总感觉是有点问题,比如Math.round(-11.5345) == -12;
参考JDK API 1.6 中讲解如下:
round
public static long round(double a)
- 返回最接近参数的
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的值。
-
参数:
-
a- 舍入为long的浮点值。
返回:
- 舍入为最接近的
long值的参数值。
-
显然,这才是round真正的应用方法:
(long)Math.floor(a + 0.5d)
这样,就没有那么多的猜想与臆断,还得费神去记忆.
Math.round(11.5)=12 (long)Math.floor(11.5+0.5)=12
Math.round(-11.5)=-11 (long)Math.floor(-11.5+0.5)=-11
Math.round(11.5345)=12 (long)Math.floor(11.5345+0.5)=12
Math.round(-11.5345)=-12 (long)Math.floor(-11.5345+0.5)=-12
Math.round(11.46)=11 (long)Math.floor(11.46+0.5)=11
Math.round(-11.46)=-11 (long)Math.floor(-11.46+0.5)=-11
Math.round(11.68)=12 (long)Math.floor(11.68+0.5)=12
Math.round(-11.68)=-12 (long)Math.floor(-11.68+0.5)=-12
.............
嘿嘿~API才是王道!(在设计上还是符合四舍五入-结果变大的原则,呵呵)
本文详细解析了Java Math.round()方法的工作原理,包括其应用规则、特殊情况及与数学四舍五入原则的关系,并通过实例展示了正确的使用方法。
244

被折叠的 条评论
为什么被折叠?



