如何比较BigInteger和double

时间:2015-07-29 07:22:23

标签: java collections double biginteger

在我的程序中有一种情况我想比较bigInteger和double。我在网上搜索了很多但是工作不正常。有人请帮助我。或者请建议好的链接。

3 个答案:

答案 0 :(得分:3)

您必须将两个值都转换为BigDecimal,然后才能比较它:

    BigInteger bi = new BigInteger("1");
    BigDecimal db = new BigDecimal(bi);
    db.compareTo(new BigDecimal(1.3d));

答案 1 :(得分:2)

BigInteger实施NumberNumber具有.doubleValue()。因此,您可以做的是:

final int cmp = Double.compare(theBigInt.doubleValue(), myDouble);
// work with cmp

(当然,还有一个问题是BigInteger具有无限的精度,不像是double;但你已经知道了,对吧?)

答案 2 :(得分:0)

这个答案是对existing answer的扩展,说明了为什么BigDecimal,而不是double,是用于比较BigInteger和double的正确常用类型。

在以下程序中,biPowerPlusOne明显大于biPower。使用double进行比较,它们都被认为等于dPower。另一方面,使用BigDecimal正确地进行比较显示biPower等于dPower,但biPowerPlusOne等于dPower。

原因是2**100+1在BigInteger和BigDecimal中是完全可表示的,但在双算术中舍入到2**100(使用**来表示取幂)

import java.math.BigDecimal;
import java.math.BigInteger;

public class Test {

  public static void main(String[] args) {
    double dPower = Math.pow(2, 100);
    BigInteger biPower = BigInteger.ONE.shiftLeft(100);
    BigInteger biPowerPlusOne = biPower.add(BigInteger.ONE);
    System.out.println("biPowerPlusOne.compareTo(biPower)="
        + biPowerPlusOne.compareTo(biPower));
    compareBoth(biPower, dPower);
    compareBoth(biPowerPlusOne, dPower);
  }

  private static void compareBoth(BigInteger bi, double d) {
    System.out.println("Comparing: " + bi + " to " + d);
    System.out.println("crossCompareDouble: " + crossCompareDouble(bi, d));
    System.out
        .println("crossCompareBigDecimal: " + crossCompareBigDecimal(bi, d));
  }

  private static int crossCompareDouble(BigInteger bi, double d) {
    return Double.compare(bi.doubleValue(), d);
  }

  private static int crossCompareBigDecimal(BigInteger bi, double d) {
    BigDecimal bd1 = new BigDecimal(bi);
    BigDecimal bd2 = new BigDecimal(d);
    return bd1.compareTo(bd2);
  }
}

输出:

biPowerPlusOne.compareTo(biPower)=1
Comparing: 1267650600228229401496703205376 to 1.2676506002282294E30
crossCompareDouble: 0
crossCompareBigDecimal: 0
Comparing: 1267650600228229401496703205377 to 1.2676506002282294E30
crossCompareDouble: 0
crossCompareBigDecimal: 1