0

I am doing this:

(obj.getValue().divide(weight)).setScale(3, RoundingMode.HALF_DOWN)

and I am getting this error :

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

Where do I need to put the setScale?

Thanks

user1260928
  • 3,269
  • 9
  • 59
  • 105
  • possible duplicate of [How can I divide properly using BigDecimal](http://stackoverflow.com/questions/10637232/how-can-i-divide-properly-using-bigdecimal) – Binkan Salaryman Sep 02 '15 at 08:18
  • 1/3 is 0.3333333333... . And this is where ``BigDecimal`` fails with having an exact decimal number representation. You may take a look for overloaded methods of [``divide``](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html). – Binkan Salaryman Sep 02 '15 at 08:22

2 Answers2

1

Or you still have the other public method of BigDecimal:

public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)

Applied to your example:

obj.getValue().divide(weight, 3, RoundingMode.HALF_DOWN);
Emilien Brigand
  • 9,943
  • 8
  • 32
  • 37
0

The exception comes from the divide method, so you cannot fix it changing something after it's executed. You actually should pass the MathContext as the second parameter to the divide method itself:

(obj.getValue().divide(weight, new MathContext(3, RoundingMode.HALF_DOWN)));

This way you explicitly say that you want to divide keeping 3 digits with HALF_DOWN rounding mode.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334