在Java中检查2个双打之间是否相等的好方法是什么 [英] What is good way to check equality between 2 doubles in Java

查看:42
本文介绍了在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

这篇关于在Java中检查2个双打之间是否相等的好方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆