简体   繁体   English

比较BigDecimal值和double值是否等于两个小数位

[英]Compare that BigDecimal value and double value are equal to two decimal places

I'm working with an API that returns a double value. 我正在使用一个返回双精度值的API。 I need to compare that value to a BigDecimal value for equality to two decimal places. 我需要将该值与BigDecimal值进行比较,以等于两位小数位。

Should I convert BigDecimal to double and then compare 我应该将BigDecimal转换为double然后比较

Math.abs(myBigDecimal.doubleValue() - apiDouble) >= .01

Or are there issues with this approach? 还是这种方法有问题? Perhaps I should convert the double into a BigDecimal and and then compare? 也许我应该将double转换为BigDecimal,然后进行比较?

No. Although IEEE double has guard bits, it cannot exactly represent a decimal value. 否。尽管IEEE double具有保护位,但它不能精确表示十进制值。 Convert the double to a BigDecimal, using rounding, and then use compareTo(). 使用舍入将double转换为BigDecimal,然后使用compareTo()。 Note that equals() takes into account decimal positions, so compareTo() is safer. 请注意,equals()考虑了小数位,因此compareTo()更安全。 You may need to round the BigDecimal as well. 您可能还需要舍入BigDecimal。

Shift desired decimal positions multiplying both doubles by 100, use Math.ceil or Math.floor, as you prefer, to get rid by the rest of decimal positions: 移位所需的小数位数,将它们的双精度数乘以100,使用Math.ceil或Math.floor(如您所愿)以除去其余的小数位数:

Math.ceil(myBigDecimal.doubleValue()*100) == Math.ceil(apiDouble*100)

this is equivalent to truncate without rounding. 这等效于不舍入而截断。 If you are worring about rounding, multiply by 1000, cast to long divide by 10 and compare. 如果您担心舍入,请乘以1000,将长除数除以10并进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM