This is the Jdk7-b147 version of BigDecimal.doubleValue()
public double doubleValue(){
if (scale == 0 && intCompact != INFLATED)
return (double)intCompact;
// Somewhat inefficient, but guaranteed to work.
return Double.parseDouble(this.toString());
}
They admit that this way is inefficient! Is there a better/faster way than to use this method?
There isn't a much better way to convert a BigDecimal
to a double
. This is because the algorithms to convert foo * 10^bar
to baz * 2^quux
efficiently, while keeping very specific rounding semantics, are extremely nasty and unpleasant -- see sun.misc.FloatingDecimal
for details, or read this paper.
BigInteger.doubleValue()
, on the other hand, does have lots of opportunities for optimization, since it needn't deal with decimal fractions, but only integers. I have a JDK patch pending that optimizes BigInteger.doubleValue()
by slightly more than two orders of magnitude, though it's still awaiting review.
Update: The fix was added in OpenJDK 8, made available to the general public on March 18, 2014.