Java Math.round函数详解
1.代码如下:
public class TestMathRound { public static void main(String[] args) {System.out.println('小数点后第一位=5');System.out.println('正数:Math.round(11.5)=' + Math.round(11.5));//12System.out.println('负数:Math.round(-11.5)=' + Math.round(-11.5));//-11System.out.println();System.out.println('小数点后第一位<5');System.out.println('正数:Math.round(11.46)=' + Math.round(11.46));//11System.out.println('负数:Math.round(-11.46)=' + Math.round(-11.46));//-11System.out.println();System.out.println('小数点后第一位>5');System.out.println('正数:Math.round(11.68)=' + Math.round(11.68));//12System.out.println('负数:Math.round(-11.68)=' + Math.round(-11.68));//-12 }}
2.结果如下,可以自己运行。
3.本来以为是四舍五入,取最靠近的整数,查了网上说有四舍六入五成双,最后还不如看源码。源码如下:
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; }
我们看到round函数会默认加0.5,之后调用floor函数,然后返回。floor函数可以理解为向下取整。
4.综上,Math.round函数是默认加上0.5之后,向下取整。
到此这篇关于Java Math.round函数详解的文章就介绍到这了,更多相关Java Math.round函数内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
