简体   繁体   中英

How to compare BigInteger with double

In my program there is a situation I wanted to compare bigInteger with double. I searched lot in net but it is not working properly.Some one please help me for th same. Or please suggest good links.

You have to convert both values to BigDecimal and then you can compare it:

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

BigInteger implements Number , and Number has .doubleValue() . Therefore, what you can do is:

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

(well, of course, there remains the problem that BigInteger has an unlimited precision, unlike double; but you're aware of that already, right?)

This answer is an expansion on an existing answer , illustrating why BigDecimal, not double, is the right common type to use for comparing BigInteger and double.

In the following program, biPowerPlusOne is clearly greater than biPower. Using double to do the comparison, they are both considered equal to dPower. On the other hand, using BigDecimal to do the comparison correctly shows biPower as equal to dPower, but biPowerPlusOne as greater than dPower.

The reason is that 2**100+1 is exactly representable in BigInteger and BigDecimal, but rounds to 2**100 in double arithmetic (using ** to represent exponentiation)

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);
  }
}

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM