0

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!

jlp
  • 1,656
  • 6
  • 33
  • 48
  • 1
    Look at the Javadoc for `MathContext`. What do you think the `4` means? – tgdavies Oct 26 '21 at 23:14
  • Does this answer your question? [How to convert BigDecimal to Double in Java?](https://stackoverflow.com/questions/19650917/how-to-convert-bigdecimal-to-double-in-java) – op_ Oct 26 '21 at 23:16
  • @tgdavies yeah, I thought it meant for the decimal places. how do I make it work for both the decimal places and the whole numbers. – jlp Oct 26 '21 at 23:19
  • I'm not sure what you want to achieve. In what way does `d1 * d2` not do what you want? – tgdavies Oct 26 '21 at 23:26
  • @tgdavies isn't it possible that only doing d1*d2 would produce a result like 9.99999999999 ? – jlp Oct 26 '21 at 23:30
  • Yes, you haven't explicitly said what behaviour you want. – tgdavies Oct 26 '21 at 23:38

3 Answers3

2

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(); 
    }
    
}
1

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;
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Use below return statement instead:

return new BigDecimal(d1).multiply(new BigDecimal(d2)).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue();
Coder
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 27 '21 at 00:01