今天使用BigDecimal的时候遇到了一个错误
//随手打出来两个数字相除
new BigDecimal("3213").divide(new BigDecimal("847"))
//报错信息是Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
//翻译过来就是 非终止小数扩展;没有精确的十进制结果。
//其实就是除出来的数字是循环小数,要求确定小数点后保留几位 所以1/3也会报错
所以JAVA中如果用BigDecimal做除法的时候一定要在divide方法中传递第二个参数进行四舍五入,否则在不整除的情况下,结果是无限循环小数时,就会抛出以上异常。
注意这个divide方法有两个重载的方法
,一个是传两个参数
的,一个是传三个参数
的:
传两个参数的方法需要传入除数和四舍五入的模式:
@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
@param roundingMode rounding mode to apply. 传入round的模式
numA.divide(numB,BigDecimal.ROUND_HALF_UP)
如果传入两个参数,遇到除不尽的小数就会根据小数点后第一位进行四舍五入操作,保留整数,如果想要保留几位小数的话就需要下面传三个参数的方法
三个参数的方法:
@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
@param scale scale of the {@code BigDecimal} quotient to be returned. 传入精度
@param roundingMode rounding mode to apply. 传入round的模式
return numA.divide(numB,4,BigDecimal.ROUND_HALF_UP);
常用的除法的取值策略
BigDecimal.ROUND_HALF_UP //小学学习的四舍五入
BigDecimal.ROUND_DOWN //向下取整
BigDecimal.ROUND_UP //向上取整
//结果小数 3.7933884298
numA.divide(numB,4,BigDecimal.ROUND_HALF_UP); //3.7934四舍五入
numA.divide(numB,4,BigDecimal.ROUND_DOWN); //3.7933直接舍去四位之后的
numA.divide(numB,3,BigDecimal.ROUND_UP); //3.794直接向上取值
原文:https://www.cnblogs.com/happyeverydaywsc/p/14876796.html