Search code examples
scalabigdecimal

What is actually the doubleValue function in BigDecimal class of Scala


The BigDecimal class in scala contains a doubleValue function. The Double is 64 Bit size...But BigDecimal may contain anynumber of digits and any number of digits after decimal point.

I tried in scala REPL to see what it returns.

Actually it is useful in writing a program to find square root of BigDecimal to provide an initial guess of square root. My doubt is how a double can store a BigDecimal. Can anybody clarify this?

scala> BigDecimal("192837489983938382617887338478272884822843716738884788278828947828784888.1993883727818837818811881818818"
)
res6: scala.math.BigDecimal = 192837489983938382617887338478272884822843716738884788278828947828784888.199388372781883781881
1881818818

scala> res6.doubleValue()
res7: Double = 1.928374899839384E71

Solution

  • It is equivalent to Java's method with the same name which is documented as:

    Converts this BigDecimal to a double. This conversion is similar to the narrowing primitive conversion from double to float as defined in The Java™ Language Specification: if this BigDecimal has too great a magnitude represent as a double, it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigDecimal value.

    It doesn't actually seem to say that, but it should return the double closest to the BigDecimal. Note that for sufficiently large numbers there are large gaps between closest doubles.

    My doubt is how a double can store a BigDecimal.

    It can't, in most cases. If you convert a BigDecimal to Double and back: BigDecimal(aBigDecimal.doubleValue), the result usually won't be equal to aBigDecimal. There's even an isExactDouble method to test it.

    But for this specific use (an initial guess of square root) that doesn't matter (OTOH, possible infinity does, but you can just test for it).