Why is the construction of Bigdecimal (double d) still there?

I noticed significant pain over this constructor (even here in Stack Overflow). People use it, although the documentation clearly states:

The results of this constructor may be somewhat unpredictable http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)

I even saw the JSR-13 APPROVED with the recommendation:

Existing specifications, which may be outdated: we suggest abandoning the BigDecimal (double) constructor, which currently produces results other than the Double.toString () method.

Despite this, the designer is not yet out of date.

I would like to hear any opinions on this matter.

+13
java api bigdecimal
Jun 29 '09 at 5:41
source share
3 answers

Obsolescence is obsolete. Parts of the APIs are marked only in exceptional cases.

So, run FindBugs as part of the build process. FindBugs has a PlugIn API, as well as open source (LGPL, IIRC).

+2
Jun 29 '09 at 12:17
source share

Given the behavior of BigDecimal(double) , in my opinion, I'm not sure if this will really be such a problem.

I would definitely not agree with the wording of the documentation in the constructor of BigDecimal(double) :

The results of this constructor may be somewhat unpredictable . One might suppose that writing new BigDecimal(0.1) in Java creates a BigDecimal that is exactly 0.1 (unscaled value 1 with a scale of 1 ), but in fact it is 0.1000000000000000055511151231257827021181583404541015625 .

(Emphasis added.)

Instead of speaking unpredictably, I think the wording should be unexpected , and even then this would be an unexpected behavior for those who do not know the limitations of representing decimal numbers with a floating point value .

As long as you remember that floating point values ​​cannot represent all decimal values ​​with precision, the value returned with BigDecimal(0.1) , which is 0.1000000000000000055511151231257827021181583404541015625 , really makes sense.

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

My guess about why the BigDecimal(double) constructor does not become obsolete is that the behavior can be considered correct, and as long as someone knows how floating point representations work, the constructor behavior is not too surprising.

+18
Jun 29 '09 at 11:54
source share

This particular constructor, like all floating point operations, is an approximation. It really is not broken, it just has flaws.
Just do your research, approach it with caution, and you will not get any surprises. You come across exactly the same when assigning double / float decimal literals.

+1
Jun 29 '09 at 5:54
source share



All Articles