I have a method that calculates 17780.00 x 115.00, the result should be 2044700.00, however, the method calculated it as 2045000.00 (seems to be rounded up for the whole number). This method will also handle numbers with decimals, eg. 0.97 x 0.5. The code looks like this:
public Double multiplyNumber(Double d1, Double d2) {
return new BigDecimal(d1).multiply(
new BigDecimal(d2),
new MathContext(4, RoundingMode.HALF_UP)).doubleValue();
}
Please advise how to make the code calculate the correct result. Thanks!
You try run this.
public class Test {
public static void main(String... strings) {
System.out.println("result "+multiplyNumber(17780.00, 115.00) );
}
public static Double multiplyNumber(Double d1, Double d2) {
return new BigDecimal(d1).multiply(
new BigDecimal(d2)).setScale(4, RoundingMode.HALF_UP).doubleValue();
}
}