qq_33376750
咆哮的橙子
2016-12-15 06:08
采纳率: 100%
浏览 1.3k
已采纳

BigDecimal的加减乘除没有效果,

贴上代码,难道我哪里搞错了么?
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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • qq_36440096
    大脸猫丶 2016-12-15 06:20
    已采纳

    return new BigDecimal((double)(a+b)).setScale(2, BigDecimal.ROUND_HALF_UP);
    @caozhy大大说要四舍五入.

    点赞 评论

相关推荐