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!
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.
You should not "instantiate" an enum but use its constants. Have you tried:
new BigDecimal(12.99).setScale(2, RoundingMode.HALF_EVEN);
Note that you could also use the string constructor:
new BigDecimal("12.99");
The other answers give good guidance regarding rounding modes - but to a certain degree they miss another crucial point. From the javadoc:
The results of this constructor can be somewhat unpredictable.
The whole point is: when you pass a double value, then floating point semantics kick in.
In other words: you intend to use a special, expensive "overhead" object to deal with arbitrary floating point numbers. But you start the thing by basing it on a value that is restricted to Java double semantics.
Go for new BigDecimal("12.99")
instead, or new BigDecimal(1299, 2)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With