Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 984
BenjaminJC Avatar asked Nov 13 '17 15:11

BenjaminJC


Video Answer


3 Answers

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.

like image 69
Mad Physicist Avatar answered Oct 15 '22 10:10

Mad Physicist


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");
like image 20
assylias Avatar answered Oct 15 '22 10:10

assylias


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

like image 38
GhostCat Avatar answered Oct 15 '22 10:10

GhostCat