25

Is there anyway to convert from double value to BigInteger?

double doubleValue = 64654679846513164.2;
BigInteger bigInteger = (BigInteger) doubleValue;

I try to cast it but it didn't work.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Krack
  • 374
  • 1
  • 4
  • 7

3 Answers3

53

If you want to store the integral part of the double into a BigInteger, then you can convert it into a BigDecimal and then into a BigInteger:

BigInteger k = BigDecimal.valueOf(doubleValue).toBigInteger();
bb94
  • 1,294
  • 1
  • 11
  • 24
  • 3
    If you actually want to take just the integral part of the double and store it in a BigInteger, this is surely the best answer? – Ed Randall Nov 24 '14 at 12:45
18

BigInteger is made for holding arbitrary precision integer numbers, not decimals. You can use the BigDecimal class to hold a double.

BigDecimal k = BigDecimal.valueOf(doublevalue);

In general, you cannot type cast a Java primitive into another class. The exceptions that I know about are the classes extending Number, such as the Long and Integer wrapper classes, which allow you to cast an int value into an Integer, and so on.

Kon
  • 10,702
  • 6
  • 41
  • 58
  • It would help to OP if you explain why type casting didn't work. – Luiggi Mendoza Jul 31 '13 at 01:39
  • 1
    @LuiggiMendoza I added a thought about the casting, but not sure if it will answer OP's problem since he seems to be confused about more general things. Just my opinion. – Kon Jul 31 '13 at 01:44
1

The process of converting a Double -> BigDecimal -> BigInteger is intensive. I propose the below: (about 500% faster)

BigInteger m = DoubleToBigInteger(doublevalue);

static BigInteger DoubleToBigInteger(double testVal) {
    long bits = Double.doubleToLongBits(testVal); 
    int exp = ((int)(bits >> 52) & 0x7ff) - 1075;
    BigInteger m = BigInteger.valueOf((bits & ((1L << 52)) - 1) | (1L << 52)).shiftLeft(exp);
    return  (bits >= 0)? m : m.negate();
}
SunsetQuest
  • 8,041
  • 2
  • 47
  • 42