Krack
Krack

Reputation: 374

is there anyway to convert from Double to BigInteger?

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.

Upvotes: 25

Views: 42400

Answers (3)

SunsetQuest
SunsetQuest

Reputation: 8817

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

Upvotes: 3

bb94
bb94

Reputation: 1304

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

Upvotes: 53

Kon
Kon

Reputation: 10810

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.

Upvotes: 18

Related Questions