Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java BigDecimal arithmaticException invalid operation

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

like image 513
Error Messages Avatar asked Mar 29 '12 19:03

Error Messages


1 Answers

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.)

like image 141
Louis Wasserman Avatar answered Sep 18 '22 17:09

Louis Wasserman