Skip to content
Advertisement

BigDecimal – to use new or valueOf

I came across two ways of getting BigDecimal object out of a double d.

  1. new BigDecimal(d)
  2. BigDecimal.valueOf(d)

Which would be a better approach? Would valueOf create a new object?

In general (not just BigDecimal), what is recommended – new or valueOf?

Advertisement

Answer

Those are two separate questions: “What should I use for BigDecimal?” and “What do I do in general?”

For BigDecimal: this is a bit tricky, because they don’t do the same thing. BigDecimal.valueOf(double) will use the canonical String representation of the double value passed in to instantiate the BigDecimal object. In other words: The value of the BigDecimal object will be what you see when you do System.out.println(d).

If you use new BigDecimal(d) however, then the BigDecimal will try to represent the double value as accurately as possible. This will usually result in a lot more digits being stored than you want. Strictly speaking, it’s more correct than valueOf(), but it’s a lot less intuitive.

There’s a nice explanation of this in the JavaDoc:

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. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

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)).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement