Search code examples
javaroundingbigdecimal

BigDecimal methods send formatted numbers


I'm trying to round my big BigDecimals off to three decimal places. For instance, let's say I have some

BigDecimal  X = 1362.59633

I wanna get:

1362.596

Here is what I'm doing:

BigDecimal Y = X.round(new MathContext(3));

But I keep getting this: 1.36E+3. What should I do in this case? Thanks


Solution

  •     BigDecimal  X = new BigDecimal(1362.59633);
        X = X.setScale(3,RoundingMode.HALF_EVEN);
        System.out.println(X); //1362.596
    

    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.