Scala 的 BigDecimal class 中的 doubleValue 函数实际上是什么

What is actually the doubleValue function in BigDecimal class of Scala

scala 中的 BigDecimal class 包含一个 doubleValue 函数。 Double 是 64 位大小......但是 BigDecimal 可能包含任意数量的数字和小数点后的任意数量的数字。

我在 scala REPL 中尝试查看它 returns。

实际上,它在编写程序以求 BigDecimal 的平方根以提供平方根的初始猜测时很有用。我怀疑 double 如何存储 BigDecimal。谁能澄清一下?

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

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

转换有损。如果该值不能表示为双精度值,则结果可能是

之一
  java.lang.Double.POSITIVE_INFINITY
  java.lang.Double.NEGATIVE_INFINITY

相当于Java的method with the same name,记录为:

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.

它实际上并没有这么说,但它应该 return 最接近 BigDecimaldouble。请注意,对于足够大的数字,最近的 doubles.

之间会有很大的差距

My doubt is how a double can store a BigDecimal.

在大多数情况下,它不能。如果将 BigDecimal 转换为 Double 并返回:BigDecimal(aBigDecimal.doubleValue),结果通常不等于 aBigDecimal。甚至还有一个 isExactDouble 方法来测试它。

但是对于这个特定的用途(平方根的初始猜测)并不重要(OTOH,可能无穷大,但你可以测试它)。