0

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
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
failure
  • 215
  • 1
  • 3
  • 12

1 Answers1

3

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249