简体   繁体   中英

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?

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

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) .

在BigInteger上调用.doubleValue() ,并将它们乘以双精度数。

Why is BigInteger#multiply() not helpful? There are really only two reasonable answers:

BigInteger a = /* whatever */;
double b = /* whatever */

// either
double result = a.multiply(new BigInteger(b)).doubleValue();
// or
double result = a.doubleValue() * b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM