2

How do you convert a double to a BigInteger, as accurately as possible? BigInteger doesn't have a valueOf(double) method. It does have a valueOf(long) method, but converting via long, would destroy any value outside the 2^64 range, and in particular I'm trying to get large numbers like 1e100 to convert to their corresponding integer values to the sixteen or so significant figures allowed by floating point precision.

rwallace
  • 31,405
  • 40
  • 123
  • 242

2 Answers2

5

You can convert the double into a BigDecimal and then into a BigInteger:

BigInteger k = BigDecimal.valueOf(doublevalue).toBigInteger();
Mathias G.
  • 4,875
  • 3
  • 39
  • 60
1

You could use BigDecimal.valueOf(double) and then call toBigIntegerExact() on that. Like,

BigInteger bi = BigDecimal.valueOf(Math.PI).toBigIntegerExact();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249