BigDecimal相关

在使用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);
问题消失




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值