概述
在使用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);
问题消失
最后
以上就是爱笑红酒为你收集整理的BigDecimal相关的全部内容,希望文章能够帮你解决BigDecimal相关所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复