java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result異常的解決方法
寫一個JAVA程序的時候出現了異常:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result。
發現報錯的語句是:
BigDecimal productPrice = avgOrderPrice.divide(price);
解決方法
原來JAVA中如果用BigDecimal做除法的時候一定要在divide方法中傳遞第二個參數,定義精確到小數點後幾位,否則在不整除的情況下,結果是無限循環小數時,就會拋出以上異常。
BigDecimal productPrice = avgOrderPrice.divide(price, 1, BigDecimal.ROUND_HALF_UP);