Welcome to follow the author's WeChat public account: Programming Coconut
I ran the unit test this afternoon and reported an error, and found a code problem about new BigDecimal(double val).
question
Business code:
/**
* 校验价格是否一致
*
* @param frontPrice 前端商品价格
* @param realPrice 商品系统价格
* @return boolean true 相等
*/
public static boolean comparePrice(BigDecimal frontPrice, BigDecimal realPrice) {
return frontPrice.compareTo(realPrice) == 0;
}
复制代码
Test code:
/**
* 前端价格
*/
BigDecimal forntPrice = new BigDecimal(0.2);
复制代码
Then test the comparePrice method always returns false, frontPrice and realPrice are obviously equal, both are 0.2.
After troubleshooting the problem, it is found that the value of frontPrice is not 0.2, but 0.200000000000000011102230246251565404236316680908203125 .
Damn, why does this happen, isn't BigDecimal an exact operation?
solve
Check out the related documentation:
Just flip it over:
Convert double type to BigDecimal type.
- The result of this constructor is somewhat unpredictable. You might think
new BigDecimal(0.1)
that creates a BigDecimal that is exactly equal to 0.1, but it is actually equal to 0.100000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double. - The String constructor is completely predictable and
new BigDecimal("0.1")
will create a BigDecimal exactly equal to 0.1, it is recommended to use the String constructor in preference. - If you must use double as the conversion source, you can use
BigDecimal.valueOf(0.1)
it, and the result it returns is accurate.
Summarize
When converting a double type to a BigDecimal type, do not use new BigDecimal(0.1)
this constructor because the result it gets is inexact.
Use BigDecimal.valueOf(0.1)
or new BigDecimal("0.1")
.
When using IDEA coding, it will give a warning prompt:
我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿。