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.
Asked
Active
Viewed 1.3k times
2
-
BigInteger will destroy that info to... – ΦXocę 웃 Пepeúpa ツ Feb 14 '18 at 10:48
-
i hope you know that `Double.MAX_VALUE` is somewhere around 1.7*10^308... – Martin Frank Feb 14 '18 at 10:50
-
@MartinFrank: No problem for a `BigInteger`. – Rudy Velthuis Feb 14 '18 at 19:59
2 Answers
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
-
1That would throw an error, because is *π* not exactly 3 anyway. If you want to avoid errors, use `toBigInteger()`. – Rudy Velthuis Feb 14 '18 at 19:54