关于java Math.round(Double a) 方法

来源:互联网 发布:jquery与javascript 编辑:程序博客网 时间:2024/05/21 08:39

首先看看API中关于这个方法怎么说的,Math.round(Double a) Returns the closest long to the argument,意思就是返回最接近参数的long,实际上这样没法理解,比如有Math.round(7.5),那么到底是返回8呢还是7呢?再如Math.round(-7.5)结果又会怎么样呢?

由此我写了一些测试代码并如下:

public class Test {public static void main(String[] args) {// 小数点后第一位 = 5System.out.println("正数:Math.round(11.5) = " + Math.round(11.5));System.out.println("负数:Math.round(-11.5) = " + Math.round(-11.5));// 小数点后第一位 < 5System.out.println("正数:Math.round(11.49) = " + Math.round(11.49));System.out.println("负数:Math.round(-11.49) = " + Math.round(-11.49));// 小数点后第一位 > 5System.out.println("正数:Math.round(11.69) = " + Math.round(11.69));System.out.println("负数:Math.round(-11.61) = " + Math.round(-11.69));}}

打印结果如下:

正数:Math.round(11.5) = 12负数:Math.round(-11.5) = -11正数:Math.round(11.49) = 11负数:Math.round(-11.49) = -11正数:Math.round(11.69) = 12负数:Math.round(-11.61) = -12

由此基本上可以得出结论:正数小数点后大于5则舍入,负数小数点后小于以及等于5都舍去,反之舍入,也可以说小数点后大于5全部加,等于5正数加,小于5全不加



0 0
原创粉丝点击