BigDecimal相关

    xiaoxiao2021-04-17  41

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

    转载请注明原文地址: https://ju.6miu.com/read-674288.html

    最新回复(0)