貼上代碼,難道我哪裡搞錯了麼?
public class Myutil {
public static double add(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.add(b2).doubleValue();
}
public static double sub(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.subtract(b2).doubleValue();
}
public static double mul(double value1, double value2) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.multiply(b2).doubleValue();
}
public static double div(double value1, double value2, int scale)
throws IllegalAccessException {
if (scale < 0) {
throw new IllegalAccessException("精確度不能小於0");
}
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.divide(b2, scale).doubleValue();
}
}
測試:
public void test1() throws IllegalAccessException{
System.out.println(Myutil.sub(1.0, 0.42));
System.out.println(Myutil.mul(4.015, 100));
System.out.println(Myutil.add(0.06, 0.01));
System.out.println(Myutil.div(303.1, 1000, 4));
}
結果
0.5800000000000001
401.49999999999994
0.06999999999999999
0.30310000000000004
return new BigDecimal((double)(a+b)).setScale(2, BigDecimal.ROUND_HALF_UP);
@caozhy大大說要四捨五入.