When converting from float
to BigDecimal
in Java and getting some unexpected results.
Notice "garbage" digits "23841858" in the first line and up to 7th line similarly in least significant digits:
for (w <- (1 to 70))
{
val wp = ten.pow(w, mc)
val onePlus :BigDecimal = one.add(one.divide(wp, mc), mc)
val flo :Float = onePlus.floatValue()
val flo_to_d :BigDecimal = BigDecimal.valueOf(flo)
println(f"""${w}: ${comp_decimals("float", onePlus, flo_to_d)}, dec=${onePlus}, flo=${flo}, flo_to_d=${flo_to_d} """)
}
I do not see this problem when trying to convert double
to BigDecimal
:
for (w <- (1 to 70))
{
val wp = ten.pow(w, mc)
val onePlus :BigDecimal = one.add(one.divide(wp, mc), mc)
val dou :Double = onePlus.doubleValue()
val dou_to_d :BigDecimal = BigDecimal.valueOf(dou)
println(f"""${w},${comp_decimals("double", onePlus, dou_to_d)}, dec=${onePlus}, dou=${dou_to_d} """ )
}
What is the fundamental difference in how conversion to BigDecimal
from float
and from double
is done in Java?
I do understand that float
only keeps 7 significant digits, while double
keeps up to 15 significant digits. But this doesn't explain the odd trailing "trash" digits when converting from float
to BigDecimal
. FWIW, this issue only happens when converting from float to BigDecimal, and not other way around.
Btw, the below code is written in Scala, but it uses only Java native functionality when it comes to BigDecimal
support. Java 8 / Scala 2.12. Java bug?