Deprecated constructor for BigDecimal.setScale(int, int) and RoundingMode enums

BenjaminJC picture BenjaminJC · Nov 13, 2017 · Viewed 12.1k times · Source

I'm trying to specify the precision of a BigDecimal value with the following: new BigDecimal(12.99).setScale(2, BigDecimal.ROUND_HALF_EVEN. However, the compiler is telling me that setScale(int, int) is deprecated.

When I've tried to use the RoundingMode enums, it's telling me that the enum may not have been initialised. How do I correctly use the enums to instantiate the BigDecimals with setScale(int, RoundingMode)?

Thanks!

Answer

Mad Physicist picture Mad Physicist · Nov 13, 2017

According to the docs, setScale(int, int), has not been recommended since Java 1.5, when enums were first introduced:

The new setScale(int, RoundingMode) method should be used in preference to this legacy method.

It was finally deprecated in Java 9.

You should call setScale(2, RoundingMode.HALF_EVEN) instead. It makes error checking much simpler, since you can't pass in an undefined enum, but you can certainly pass in an integer mode which is undefined.