Pregunta

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), then valueOf() should be preferred: it can do caching of common values (as seen on Integer.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?

¿Fue útil?

Solución

Firstly, any time you convert from a double to BigDecimal you should take a step back and ask yourself whether you're really doing the right thing to start with. For example, if you've done this by parsing from a String to a double, then you should probably go straight from a String to a BigDecimal. I'm generally wary of this conversion, as it usually suggests someone is using an inappropriate type elsewhere.

Beyond that, they do different things: the constructor gives a BigDecimal which represents the exact same number as the double; valueOf gives a BigDecimal which represents the number given by the double value's canonical string representation. They're simply different things, and you should know which one you want when you try to use one.

Given that I'd try to avoid getting into this situation to start with, it's hard to give examples of when each is more appropriate, but if you've unavoidably converting text to a double, then lost the original text, but want to get back to that value, then using valueOf is likely to give you a better result. If you've performed a bunch of arithmetic operations on double values, then the constructor might be more appropriate. But it's really very context-sensitive, and as I say in most cases I'd probably choose a redesign rather than picking either option.

Otros consejos

Look at the sources of BigDecimal and it is kind of obvious that passing a double into valueOf is less efficient than calling the constructor

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top