BigDecimal setScale method returning strange results

258 Views Asked by At

I have an area where I am doing the following:

BigDecimal number = new BigDecimal(String.valueOf("81.4125"));

The above is a BigDecimal with scale set to 4;

But If I do the following:

BigDecimal roundedNumber = number.setScale(2, RoundingMode.HALF_UP);

It returns 81.41 which is clearly incorrect. If I run the same experiment with 404.1675, it returns 404.17!! Is this expected or is it a certain behaviour recorded for BigDecimal Classes?

KR,

1

There are 1 best solutions below

0
On BEST ANSWER

I think that this is actually the correct rounding using the scale of 2 and the RoundingMode HALF_UP.

The Javadocs for BigDecimal define ROUND_HALF_UP to do the following:

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.

So those test cases look like they turned out correct for the specifications.

Since the scale is set to 2, you will get two digits in your decimal number, so it will look at the 3rd digit to determine which way to round. Hopefully this helps!