I am trying to convert string values into BigDecimal and then perform my calculation, but the output is not as expected. Please find the code below:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Test {
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("320000");
BigDecimal b2 = new BigDecimal(0.1);
BigDecimal b3 = new BigDecimal("9.6");
BigDecimal b5 = new BigDecimal(320000);
BigDecimal b6 = new BigDecimal(9.6);
BigDecimal b4 = (
b1.multiply(b2)
).multiply(
b3.divide(b1, RoundingMode.HALF_UP)
);
System.out.println(b4.setScale(4, RoundingMode.HALF_UP));
BigDecimal b7 = (
b5.multiply(b2)
).multiply(
b6.divide(b5, RoundingMode.HALF_UP)
);
System.out.println(b7.setScale(4, RoundingMode.HALF_UP));
}
}
The out is shown below for both the instances:
0.0000
0.9600
When I use the instantiate the numbers as BigDecimal rather than converting them from string in the second instance I am getting the desired output.
Can you please let me know why it is happening and how could I get the desired output of 0.9600 in the first instance.