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?

durron597
  • 31,968
  • 17
  • 99
  • 158
  • 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.) – Louis Wasserman Feb 06 '13 at 22:40
  • Awesome! Do you have a link to the patch? – durron597 Feb 06 '13 at 22:42
  • 2
    https://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`](http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html) -- you can see how messy it is there. – Louis Wasserman Feb 06 '13 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 Feb 06 '13 at 22:47

1 Answers1

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.

durron597
  • 31,968
  • 17
  • 99
  • 158
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • @LouisWasserman did they remove the "voting for bugs" thing they used to have awhile back? I found [this](http://bugs.sun.com/view_bug.do?bug_id=7131192), I notice it hasn't been updated since July. Do you have more information on WHEN they will look at it? – durron597 Feb 07 '13 at 15:08