0

Need to convert a double value to big integer or long value. tried with big integer but the converted value differs from original value.

double doub = 123456789123456789123456789d;
BigDecimal bd = BigDecimal.valueOf(doub);
System.out.println("value=="+bd.toBigInteger());

value==123456789123456790000000000

Expected output: 123456789123456789123456789
Heisenberg
  • 147
  • 1
  • 4
  • 14

1 Answers1

7

You are losing all the precision with your first line.

double doub = 123456789123456789123456789d;
System.out.println(doub);

Will print the following:

1.2345678912345679E26

Which is equal to your

123456789123456790000000000

The reason being that 123456789123456789123456789 cannot be precisely represented with a double-precision 64-bit IEEE 754 floating point. Because of this you never actually have the value 123456789123456789123456789 in the first place to convert into a BigInteger. If you have your value as a String you could convert it into a BigInteger like this:

BigInteger b = new BigInteger("123456789123456789123456789");
bhspencer
  • 13,086
  • 5
  • 35
  • 44