Unpredictability of the BigDecimal(double) constructor

Why does this constructor really exists?

It converts the actual represented value of double to a BigDecimal. The whole point of BigDecimal is to give as much precision as possible and that is what this constructor does.

If you want to take the value you would get with a small amount of rounding the Double.toString(double) uses you can use

System.out.println(BigDecimal.valueOf(0.1));

prints

0.1

When should I use the new BigDecimal(double val) constructor

When you want to know the value double really represents. You can apply your own rounding as required.

When you use double you should always apply a sensible rounding. But, if you did that you may find you don't need BigDecimal. ;)


When should I use the new BigDecimal(double val) constructor?

Preferably - nowhere.

If you are willing to play with BigDecimals, using constructor with double means loosing all benefits of exact number presentation.

Why does this constructor really exists?

Because sometimes you have only double, that you want to translate to BigDecimal. Forcing you to use .toString() inbetween would be just silly ;)


Because if you already begin with a double value as data, you have already lost that precission. So not having it would force you to convert it to String for BigDecimal to convert it back.

And also, maybe sometimes you just need that value.

Tags:

Java