Math.round()

在 JAVA 中四舍五入采用 Math.round(T a) 函数,函数返回的是一个 long 类型的长整型,参数 a 能够是 double 也能够是 float。java

查看 JDK 源码:less

  

public static long round(double a) {
        if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5
            return (long)floor(a + 0.5d);
        else
            return 0;
}

  

public static double floor(double a) {
        return StrictMath.floor(a); // default impl. delegates to StrictMath
}

  

 public static double floor(double a) {
     return floorOrCeil(a, -1.0, 0.0, -1.0);
 }

  

其实具体实现仍是挺复杂的。函数

须要注意的是 a 为负数的状况。spa

 1 System.out.println("小数点后第一位=5");
 2 System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));
 3 System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));
 4 System.out.println();
 5 System.out.println("小数点后第一位<5");
 6 System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));
 7 System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));
 8 System.out.println();
 9 System.out.println("小数点后第一位>5");
10 System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));
11 System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));

输出结果是:code

小数点后第一位=5
正数:Math.round(11.5)=12
负数:Math.round(-11.5)=-11

小数点后第一位<5
正数:Math.round(11.46)=11
负数:Math.round(-11.46)=-11

小数点后第一位>5
正数:Math.round(11.68)=12
负数:Math.round(-11.68)=-12

正数和咱们平时学的同样,负数在小数点后第一位为5时,直接舍去小数部分,大于5时减一,小于5时直接舍去小数部分。blog

相关文章
相关标签/搜索