什么方法检查大于双精度更好



我有这个:

double a = ...;
double b = ...;
if (a < b) {
    ....
} else
....

但我不能将这种方法用于浮点(双),因为,例如:

double a = 5 - 4.9 = 0.999999964;
double b = 0.1;
a < b = true // when it should be false

我在考虑两种可能的解决方案

  • 第一个使用乘以某个数字、强制转换为int并取整的方法:

    (int) Math.round(a * 10_000) < (int) Math.round(b * 10_000);

  • 或者以这种方式使用ε:

    double decimaPrecision = 0.00001; double max = Math.max(a, b); double min = Math.min(a, b); return Math.abs(a/ b) > (1.0 + decimaPrecision);

我应该使用什么方法?你知道更好的检查方法吗?你知道做这类事情的3pp吗?

您可以使用BigDecimal进行这种类型的比较:

BigDecimal a = new BigDecimal("5").subtract(new BigDecimal("4.9")); // == 0.1
BigDecimal b = new BigDecimal("0.1"); // == 0.1
System.out.println(a.compareTo(b)); // 0 - they are equal

输出

0

最新更新