12

I cant find why I got a java.lang.ArithmeticException: Invalid operation while using big decimal.

public static String E (int exponent, String value){
BigDecimal ten= new BigDecimal("10");
BigDecimal tempValue=new BigDecimal (value);
return tempValue.multiply(ten.pow(exponent)).toString();
}

Some of the exponents have values such as -27. Is there any way around this since it would be difficult to store the original values with many zeros. I chose BigDecimal since I needed to precision.

Thank you

kam1l
  • 73
  • 1
  • 5
Error Messages
  • 304
  • 1
  • 3
  • 15

2 Answers2

12

If you are raising things to negative exponents, you must specify a MathContext in BigDecimal.pow(int, MathContext) so it knows how much precision to use -- otherwise, BigDecimal will try to compute it to infinite precision, which is not possible for some values.

(Unless you can be absolutely sure that the operation you're doing has an exact result with a finite number of digits.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • i am absolutely sure that it doesnt have an infinite precision. I still get that error though. Using double will not reach as far while some operations performed tend to be done near 0. I dont see how 10 to the power off something can be an infinite precision and a scientific calculator can hold the value up to -99. Otherwise would there be a better way to represent this? – Error Messages Mar 29 '12 at 21:28
  • Could you give us the stack trace of the exception? – Louis Wasserman Mar 29 '12 at 21:51
  • 1
    @ErrorMessages `pow(int)` will, when given a negative number, throw a ArithmeticException. Always. http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#pow%28int%29 – Joni Mar 29 '12 at 21:54
  • 1
    Right. I should've noticed that. That said, @ErrorMessages, it looks like your method is actually equivalent to `scaleByPowerOfTen`, which might be simpler. – Louis Wasserman Mar 29 '12 at 21:57
3

To multiply a BigDecimal by a power of 10 it's probably clearer to the reader (and more efficient, too) to use movePointLeft and movePointRight:

Instead of tempValue.multiply(ten.pow(exponent)) you would use tempValue.movePointRight(exponent).

Joni
  • 108,737
  • 14
  • 143
  • 193