Skip to content
Advertisement

How to round a BigDecimal before the decimal?

I have a BigDecimal like this
var a = new BigDecimal("1234.56") and I want to round it to commercially to two places before the decimal, so that I get something equivalent to
var b = new BigDecimal("1200.00") so that
(new BigDecimal("1200.00")).equals(b).

My best approach currently is
var b = new BigDecimal(a.setScale(-2, RoundingMode.HALF_UP).toPlainString()).setScale(2);
but I’m unsure if this is the right way because compared to positive scales it seems rather verbose. Is this the best way to do it?

Advertisement

Answer

You don’t need to use new BigDecimal if you’re using setScale, because it’s already returning a new instance if it needs to:

Returns a BigDecimal whose scale is the specified value

Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

So, you can write it more easily:

BigDecimal b = a.setScale(-2, RoundingMode.HALF_UP).setScale(2);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement