BigDecimal dividend = new BigDecimal("10"); BigDecimal divisor = new BigDecimal("3"); BigDecimal result = dividend.divide(divisor); // 未指定精度和舍入模式 System.out.println(result); //输出 Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(BigDecimal.java:1693) at com.example.demo.controller.Test.main(Test.java:26)
"If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations."
要使用
BigDecimal
时,要记得指定精度,避免因为精度问题带来的损失。
4. BigDecimal转String,科学计数法展示问题
System.out.println( new BigDecimal("0.0000000000001").toString()); BigDecimal bigDecimal = new BigDecimal("1E+12"); System.out.println(bigDecimal.toString()); //输出 1E-13 //输出 1E+12