Note the use of new BigDecimal(double val)

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:

Bigdecimal-doc.png

Just flip it over:

Convert double type to BigDecimal type.

  1. 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.
  2. 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.
  3. 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").

BigDecimal-example.png

When using IDEA coding, it will give a warning prompt:

Bigdecimal-idea.png

我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿

Guess you like

Origin juejin.im/post/7122734648517459976