6

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?

4
  • 1
    Accuracy is pretty crucial, and the logic to convert a BigDecimal to a double is hard. (That said, I've got a JDK patch pending review to speed up BigInteger.doubleValue() by a little over two orders of magnitude.) Commented Feb 6, 2013 at 22:40
  • Awesome! Do you have a link to the patch?
    – durron597
    Commented Feb 6, 2013 at 22:42
  • 2
    bugs.openjdk.java.net/attachment.cgi?id=254&action=diff is the patch to optimize BigInteger.{float,double}Value(). The logic for Double.parseDouble, which is nearly the same as what you'd need to convert BigDecimal to double, is in sun.misc.FloatingDecimal -- you can see how messy it is there. Commented Feb 6, 2013 at 22:43
  • Louis, this is exactly what I was looking for. If you make these comments into an answer, I'll checkmark you.
    – durron597
    Commented Feb 6, 2013 at 22:47

1 Answer 1

11

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.

1
  • @LouisWasserman did they remove the "voting for bugs" thing they used to have awhile back? I found this, I notice it hasn't been updated since July. Do you have more information on WHEN they will look at it?
    – durron597
    Commented Feb 7, 2013 at 15:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.