首页 > 其他 > 详细

Math.round()

时间:2014-12-06 16:47:05      阅读:366      评论:0      收藏:0      [点我收藏+]

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

查看 JDK 源码:

  

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 为负数的情况。

 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));

输出结果是:

小数点后第一位=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时直接舍去小数部分。

 

Math.round()

原文:http://www.cnblogs.com/baisu/p/4148360.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!