import java.math.BigDecimal;
import java.util.Objects;
public class DecimalTest {
public static void main(String[] args) {
BigDecimal dealPrice = new BigDecimal(1);
BigDecimal dealBuildingArea = new BigDecimal(3);
if (!Objects.isNull(dealPrice) && !Objects.isNull(dealBuildingArea)) {
BigDecimal dealUnitPrice =
divideMethod(dealPrice, dealBuildingArea).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(dealUnitPrice);
}
}
private static BigDecimal divideMethod(BigDecimal obj1, BigDecimal obj2){
if(null==obj1 || null==obj2 || obj2.compareTo(BigDecimal.ZERO)==0){
return BigDecimal.ZERO;
}
return obj1.divide(obj2,2,BigDecimal.ROUND_HALF_UP);
}
}
以上代码能正常执行且达到预期目的。
如果return obj1.divide(obj2,2,BigDecimal.ROUND_HALF_UP);这一行代码,去掉2,BigDecimal.ROUND_HALF_UP则会报错如下:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1690)
at DecimalTest.divideMethod(DecimalTest.java:19)
at DecimalTest.main(DecimalTest.java:10)