'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?



Solution 1:[1]

If you are using your BigDecimal objects to store currency values, then I strongly recommend that you do NOT involve any double values anywhere in their calculations.

As stated in another answer, there are known accuracy issues with double values and these will come back to haunt you big time.

Once you get past that, the answer to your question is simple. Always use the constructor method with the String value as the argument to the constructor, as there is no valueOf method for String.

If you want proof, try the following:

BigDecimal bd1 = new BigDecimal(0.01);
BigDecimal bd2 = new BigDecimal("0.01");
System.out.println("bd1 = " + bd1);
System.out.println("bd2 = " + bd2);

You'll get the following output:

bd1 = 0.01000000000000000020816681711721685132943093776702880859375
bd2 = 0.01

See also this related question

Solution 2:[2]

Basically valueOf(double val) just does this:

return new BigDecimal(Double.toString(val));

Therefore -> yep, a new object will be created :).

In general I think it depends upon your coding style. I would not mixure valueOf and "new", if both are the same outcome.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 DXTR66