losing precision converting from java BigDecimal to double

后端 未结 5 1479
遥遥无期
遥遥无期 2020-12-15 08:56

I am working with an application that is based entirely on doubles, and am having trouble in one utility method that parses a string into a double. I\'ve found a fix where

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 09:50

    If it's entirely based on doubles ... why are you using BigDecimal? Wouldn't Double make more sense? If it's too large of value (or too much precision) for that then ... you can't convert it; that would be the reason to use BigDecimal in the first place.

    As to why it's losing precision, from the javadoc

    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.

提交回复
热议问题