在Java中检查2个双打之间是否相等的好方法是什么
对于Double/Float,当从十进制转换为二进制表示形式时,会存在一些舍入误差和精度损失.例如,将float设置为"6.1",然后再次打印出来,则可能会得到报告值,例如"6.099999904632568359375".这是检查2个Double对象是否相等的更好选择:使用BigDecimal或者(Math.abs(double1-double2)< epsilon)
For Double/Float, there are some rounding errors and loss of precision when converting from decimal to binary representation. For example, setting float to "6.1" and then printing it out again, you may get a reported value of something like "6.099999904632568359375". Which is the better option for checking equality of 2 Double objects : Using BigDecimal or (Math.abs(double1 - double2) < epsilon)
这取决于您的用例.如果您使用货币,请使用BigDecimal.否则,如果您可以接受近似值,请使用 Math.abs(double1-double2)<epsilon
It depends on your usecase. If you work with currency, go for BigDecimal.
Otherwise if you can live with approximations use Math.abs(double1 - double2) < epsilon