码迷,mamicode.com
首页 > 其他好文 > 详细

Math.round()

时间:2014-12-06 16:49:20      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   sp   java   on   div   log   bs   

在 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()

标签:style   blog   color   sp   java   on   div   log   bs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!