Search code examples
javabigdecimal

Java's BigDecimal setScale


Thanks for any advice.

Why is this:

import java.math.*;

public class bdt {

    public static void main (String [] args) {

        BigDecimal a = new BigDecimal ("1.0");
        BigDecimal b = new BigDecimal ("3.0");
        BigDecimal c = new BigDecimal ("0.0");

        c = a.divide (b,MathContext.DECIMAL128);
        c.setScale (2,RoundingMode.HALF_UP);
        System.out.println (a.toString ());
        System.out.println (b.toString ());
        System.out.println (c);

    }

}

yielding this:

1.0
3.0
0.3333333333333333333333333333

instead of:

1.0
3.0
0.33

Solution

  • Because BigDecimal is immutable you have to assign the result of the call to setScale() to c,

    c = c.setScale(2, RoundingMode.HALF_UP);
    

    the linked Javadoc says (in part) Returns a BigDecimal whose scale is the specified value.

    tl;dr It doesn't modify c in place.