This question is a follow up to the question (BigDecimal - to use new or valueOf) and its accepted answer.
To reiterate the question and answer for convenience:
BigDecimal
has two methods:
double d = 0.1;
BigDecimal bd1 = new BigDecimal(d);
BigDecimal bd2 = BigDecimal.valueOf(d);
Which one is better? The answer shows that these methods do not produce the same result:
System.out.println(bd1);
System.out.println(bd2);
displays:
0.1000000000000000055511151231257827021181583404541015625
0.1
In the answer, the answerer states :
In general, if the result is the same (i.e. not in the case of
BigDecimal
, but in most other cases), thenvalueOf()
should be preferred: it can do caching of common values (as seen onInteger.valueOf()
) and it can even change the caching behaviour without the caller having to be changed. new will always instantiate a new value, even if not necessary (best example:new Boolean(true)
vs.Boolean.valueOf(true)
).
My question is: can we get some practical examples of when, specifically, we should use BigDecimal.valueOf()
and when we should use new BigDecimal()
?? The answerer says "use valueOf()
if the result is the same" but that doesn't help us to know when to use it (if ever?) for BigDecimal
.
Specifically, which is preferable:
0.1000000000000000055511151231257827021181583404541015625
or
0.1
? And why?