I have a function that receives two BigDecimal numbers say bd1 and bd2 as paramters. The function should subtract bd1 - db2 and return
Scale of bd1 and bd2 is both 2 and the result should also have scale of 2 only
But using subtract is scaling out to full decimal representation
I want the scale set at 2 and tried using setScale , but setScale is expeccting
a roundingmode and unclear on which rounding mode to use to get exact result limited to scale 2
The need is to get the exact subtracted value (bd1 - bd2) with scale of 2 .
In this case i need 15.04 without rounding as am getting these value from another application and i dont want to change the values by adding Rounding mode
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
Actual result is 15.04