站内搜索

workerdance.com — Trusted craft, unfailing commitment
返回文章列表
后端开发

BigDecimal相关

本文写于 2017 年,文中涉及的软件版本可能已有变化,核心排查思路仍可参考。

在使用FindBugs对代码进行审查时, 发现了一个Scary类别的错误, 错误消息: BigDecimal constructed from double that isn’t represented precisely

代码如下:

BigDecimal taxRate = new BigDecimal(0.09);

FindBugs给的完整描述为

BigDecimal constructed from double that isn't represented precisely
This code creates a BigDecimal from a double value that doesn't translate well to a decimal number.
For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1
(an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.
You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation of the double to create the
BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1).

打印了一下taxRate, 发现结果是:  0.0899999999999999966693309261245303787291049957275390625

报的描述大概意思是: 用double不能保证精度, 建议使用: BigDecimal.valueOf方法

代码改为:

BigDecimal taxRate = BigDecimal.valueOf(0.09);

问题消失

workerdance
workerdance

记录开发与运维中的实践和踩坑。