big decimal number rounding

Limit BigDecimal to n decimal places

Limit BigDecimal to n places only

In java, when you are working with currency and other important precision based calculation, you will use Big Decimal. In some cases you might want to round the number to two (2) decimal places only or, lets say, to n, decimal places.

When to use limited decimal places

There are a couple of cases where you need to round or just to limit the number of decimal places. Once example is when you are working on the currency, after conversion, you may get a long decimal and in that case – rounding will be necessary.

Using big decimal functions for rounding the numbers

BigDecimal bill = new BigDecimal("23.9876546");
bill.setScale(2, RoundingMode.DOWN);

The above will be produce 23 this is because of the flag passed to it of RoundingMode.DOWN. There are other important flags that needs to be passed when rounding.

All the flags are here.