Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to multiple a BigInteger by a Double in Java?

I have a very large number (number1) stored as a BigInteger, and a double (number2). I plan to multiply number1 and number2, and store the result as a double.

Using the multiply() method has not helped me achieve this. What is the way forward?

like image 259
jII Avatar asked Nov 28 '22 14:11

jII


2 Answers

In order to preserve the arbitrary precision as long as possible, do the multiplication in BigDecimal, and then convert the result to double, like this:

BigDecimal tmp = new BigDecimal(myBigInteger);
tmp = tmp.multiply(new BigDecimal(myDouble));
double res = tmp.doubleValue();
like image 74
Sergey Kalinichenko Avatar answered Dec 16 '22 01:12

Sergey Kalinichenko


The simplest solution is probably big.doubleValue() * myDouble.

This won't be particularly fast, unfortunately, since BigInteger.doubleValue() has a notably slow implementation. (It might be faster in the future...perhaps if Oracle applies my patch.)

Alternately, you can round a double directly to a BigInteger using Guava's DoubleMath.roundToBigInteger(double, RoundingMode).

like image 41
Louis Wasserman Avatar answered Dec 16 '22 01:12

Louis Wasserman