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!
CodePudding user response:
Rounding only deals with digits after the decimal place. To round at places to the left, divide, round, multiply back:
public Double multiplyNumber(Double d1, Double d2) {
return new BigDecimal(d1)
.multiply(new BigDecimal(d2))
.divide(BigDecimal.TEN.pow(3), new MathContext(0, RoundingMode.HALF_UP))
.multiply(BigDecimal.TEN.pow(3))
.doubleValue();
}
BTW, this also produces the value you want:
public Double multiplyNumber(Double d1, Double d2) {
return d1 * d2;
}
CodePudding user response:
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();
}
}
CodePudding user response:
Use below return statement instead:
return new BigDecimal(d1).multiply(new BigDecimal(d2)).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue();