public static void main(String[] args) throws IOException {
System.out.println(Math.round(11.5));//12
System.out.println(Math.round(-11.5));//-11
System.out.println(Math.round(11.6));//12
System.out.println(Math.round(-11.6));//-12
System.out.println(Math.round(0.5));//1
System.out.println(Math.round(-0.5));//0
}
1、Math.round()方法是用来求四舍五入的。由上面运行结果的对比来看,除了负数有0.5(如-11.5)的情况外,其余的都是数的绝对值四舍五入,再加上相对应的正负号。
2、负数有0.5(如-11.5)的情况:
Math.round()在API中有这样的描述:Returns the closest long to the argument, with ties rounding to positive infinity
返回的是一个最接近参数的long值,同时向正无穷方向取舍。
Math.round(11.5) ,首先与 11.5最接近的有两个整数 11 和 12,取较大的那结果就是12;
Math.round(-11.5),首先与 -11.5最接近的有两个整数 -11 和 -12,取较大的那结果就是-11;
Math.round(0.5),首先与 0.5最接近的有两个整数 0 和 1,取较大的那结果就是1;
Math.round(-0.5),首先与 -0.5最接近的有两个整数 -1 和 0,取较大的那结果就是0;