Why is the Bigdecimal(double d) construction still around?

后端 未结 3 432
广开言路
广开言路 2020-12-11 15:20

I\'ve noticed substantial pain over this constructor (even here on Stack Overflow). People use it even though the documentation clearly states:

Th

相关标签:
3条回答
  • 2020-12-11 15:47

    That particular constructor, like all floating point operations, is an approximation. It's not really broken, it just has shortcomings.
    Just do your research, approach it with care, and you won't get any surprises. You run into exactly the same thing when assigning decimal literals to doubles/floats.

    0 讨论(0)
  • 2020-12-11 15:48

    Considering the behavior of BigDecimal(double) is correct, in my opinion, I'm not too sure it really would be such a problem.

    I wouldn't exactly agree with the wording of the documentation in the BigDecimal(double) constructor:

    The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.

    (Emphasis added.)

    Rather than saying unpredictable, I think the wording should be unexpected, and even so, this would be unexpected behavior for those who are not aware of the limitations of representation of decimal numbers with floating point values.

    As long as one keeps in mind that floating point values cannot represent all decimal values with precision, the value returned by using BigDecimal(0.1) being 0.1000000000000000055511151231257827021181583404541015625 actually makes sense.

    If the BigDecimal object instantiated by the BigDecimal(double) constructor is consistent, then I would argue that the result is predictable.

    My guess as to why the BigDecimal(double) constructor is not being deprecated is because the behavior can be considered correct, and as long as one knows how floating point representations work, the behavior of the constructor is not too surprising.

    0 讨论(0)
  • 2020-12-11 15:57

    Deprecation is deprecated. Parts of APIs are only marked deprecated in exceptional cases.

    So, run FindBugs as part of your build process. FindBugs has a detector PlugIn API and is also open source (LGPL, IIRC).

    0 讨论(0)
提交回复
热议问题