Search code examples
javamathbigdecimal

How to limit BigDecimal to a fixed fractions amount?


I'm trying to create a BigDecimal class that has always a fixed maximum fractions count. But when printing that number, it is not cut to the fractions I defined in scale. Why?

class MyDecimal extends BigDecimal {
    public MyDecimal(double val) {
        super(val); 
        setScale(4, RoundingMode.HALF_UP);
    }
}


Sysout(new MyDecimal(0.0001));
//0.000100000000000000008180305391403130954586231382563710212707519531254

Solution

  • BigDecimal is immutable, and should not be extended. setScale() does not modify the BigDecimal instance. It returns a copy of the BigDecimal instance with the scale modified (as every other "mutating" method of BigDecimal, since it's immutable). Calling it and ignoring the returned value is thus useless.

    Instead of extending BigDecimal, create a factory method:

    public static BigDecimal createWithScale4(double d) {
        BigDecimal temp = new BigDecimal(d);
        return temp.setScale(4);
    }