Search code examples
javamathbigdecimal

What is the difference between BigDecimal movePointRight and scaleByPowerOfTen?


With the following code:

BigDecimal x = new BigDecimal("34.5678");
BigDecimal a = x.movePointRight(3);
BigDecimal b = x.scaleByPowerOfTen(3);
BigDecimal c = x.movePointRight(-3);
BigDecimal d = x.scaleByPowerOfTen(-3);
  • a and b are both 34567.8 and c and d are both 0.0345678.
  • a.scale() and b.scale are both 1 and c.scale() and d.scale() are both 7.

In what circumstances do these two methods produce different results?


Solution

    • movePointRight will prevent a negative scale from occurring if it results in one.
    • scaleByPowerOfTen will not prevent this.

    Example code:

    import java.math.BigDecimal;
    
    public class BigDecimalScale {
      public static void main(String... args) {
        long base = 12345;
        int scale = 4;
    
        BigDecimal number = BigDecimal.valueOf(base, scale);
        System.out.println(number);
        BigDecimal pointRight = number.movePointRight(5);
        System.out.println(pointRight + "; my scale is " + pointRight.scale());
        BigDecimal scaleBy = number.scaleByPowerOfTen(5);
        System.out.println(scaleBy + "; my scale is " + scaleBy.scale());
      }
    }
    

    Result:

    1.2345
    123450; my scale is 0
    1.2345E+5; my scale is -1