Java:检查两个双精度值是否匹配特定的小数位数 [英] Java: Check if two double values match on specific no of decimal places

查看:71
本文介绍了Java:检查两个双精度值是否匹配特定的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较这两个值将得出 true:

Comparing those two values shall result in a "true":

53.9173333333333  53.9173


推荐答案

如果要 a = 1.00001 b = 0.99999 被标识为相等:

If you want a = 1.00001 and b = 0.99999 be identified as equal:

return Math.abs(a - b) < 1e-4;

否则,如果要 a = 1.00010 b = 1.00019 被确定为相等,并且 a b 是正数,不是正数:

Otherwise, if you want a = 1.00010 and b = 1.00019 be identified as equal, and both a and b are positive and not huge:

return Math.floor(a * 10000) == Math.floor(b * 10000);
// compare by == is fine here because both sides are integral values.
// double can represent integral values below 2**53 exactly.

否则,使用 truncate 方法,如图所示在中是否有任何函数可以在Java中截断double?

Otherwise, use the truncate method as shown in Are there any functions for truncating a double in java?:

BigDecimal aa = new BigDecimal(a);
BigDecimal bb = new BigDecimal(b);
aa = aa.setScale(4, BigDecimal.ROUND_DOWN);
bb = bb.setScale(4, BigDecimal.ROUND_DOWN);
return aa.equals(bb);

这篇关于Java:检查两个双精度值是否匹配特定的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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