不同方法的取舍原则:
ceil:天花板,往大里取
floor:地板,往小里取
round:正数:四舍五入,5是分界点 负数:小数大于5(Math.round(-0.51)输出是-1,-0.5则是0),往小里取,反之,则往大里取
System.out.println(Math.round(11.6));//12 System.out.println(Math.round(11.2));//11 System.out.println(Math.round(11.5));//12 System.out.println(Math.round(-11.6));//-12 System.out.println(Math.round(-11.5));//-11 System.out.println(Math.round(-11.2));//-11 System.out.println(""); System.out.println(Math.ceil(11.2));//12 System.out.println(Math.ceil(11.5));//12 System.out.println(Math.ceil(11.6));//12 System.out.println(Math.ceil(-11.2));//-11 System.out.println(Math.ceil(-11.5));//-11 System.out.println(Math.ceil(-11.6));//-11 System.out.println(""); System.out.println(Math.floor(11.2));//11 System.out.println(Math.floor(11.5));//11 System.out.println(Math.floor(11.6));//11 System.out.println(Math.floor(-11.2));//-12 System.out.println(Math.floor(-11.5));//-12 System.out.println(Math.floor(-11.6));//-12
BigDecimal
1.解决小数计算失去精度问题
BigDecimal bd1 = new BigDecimal("0.001"); BigDecimal bd2 = new BigDecimal("0.009"); double add = bd1.add(bd2).doubleValue(); System.out.println(add);
得到正确的0.01
2.小数位数保留
double db = 1.2346013123; BigDecimal dd = new BigDecimal(db).setScale(2,BigDecimal.ROUND_HALF_UP );//保留两位,小数四舍五入 System.out.println(dd);