减去BigDecimal而不进行舍入

时间:2018-02-08 03:45:20

标签: java

我有一个函数接收两个BigDecimal数字,说bd1和bd2作为参数。该函数应减去bd1 - db2并返回

bd1和bd2的比例均为2,结果也应仅为2 但是使用减法是缩小到完整的十进制表示 我希望将比例设置为2并尝试使用setScale,但是setScale是expeccting 舍入模式并且不清楚使用哪种舍入模式将精确结果限制为2级

需要获得标度为2的精确减去值(bd1 - bd2)。 在这种情况下,我需要15.04没有舍入,因为我从另一个应用程序获取这些值,我不想通过添加舍入模式来更改值

    BigDecimal bd1 = new BigDecimal(30.18);
    BigDecimal bd2 = new BigDecimal(15.14);

    BigDecimal diff =  bd1.subtract(bd2);
    System.out.println("bd1.subtract(bd2)       " + diff);   

    System.out.println("RoundingMode.DOWN       " + diff.setScale(2, RoundingMode.DOWN));
    System.out.println("RoundingMode.FLOOR      "  + diff.setScale(2, RoundingMode.FLOOR));

    System.out.println("RoundingMode.UP         " +diff.setScale(2, RoundingMode.UP));

    System.out.println("RoundingMode.CEILING    " + diff.setScale(2, RoundingMode.CEILING));

    System.out.println("RoundingMode.HALF_UP    " + diff.setScale(2, RoundingMode.HALF_UP));



Result
------
bd1.subtract(bd2)       15.03999999999999914734871708787977695465087890625
RoundingMode.DOWN       15.03
RoundingMode.FLOOR      15.03
RoundingMode.UP         15.04
RoundingMode.CEILING    15.04
RoundingMode.HALF_UP    15.04

实际结果为15.04

1 个答案:

答案 0 :(得分:1)

您正在使用BigDecimal初始化double,因此它的精确度不足。请使用String作为构造函数的参数:

BigDecimal bd1 = new BigDecimal("30.18");
BigDecimal bd2 = new BigDecimal("15.14");

BigDecimal diff =  bd1.subtract(bd2);
System.out.println("bd1.subtract(bd2)  " + diff);