Java BigDecimal arithmaticException invalid operation

I cannot find why I received java.lang.ArithmeticException: Invalid operation when using a large decimal number.

 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 indicators have values, such as -27 . Is there any way around this, since it would be difficult to preserve the original values ​​with many zeros. I chose BigDecimal because I needed precision.

thanks

+6
source share
2 answers

If you increase the value to negative values, you must specify the MathContext in BigDecimal.pow(int, MathContext) so that it knows what precision to use, otherwise BigDecimal will try to calculate it to infinite accuracy, which is impossible for some values.

(If you cannot be absolutely sure that the operation you are performing has an accurate result with a finite number of digits.)

+4
source

To multiply BigDecimal by a power of 10, it is probably clearer to the reader (and more efficient) for using movePointLeft and movePointRight :

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

+2
source

Source: https://habr.com/ru/post/911974/


All Articles