Search code examples
javabigdecimal

BigDecimal acting weird


I have a BigDecimal a1

BigDecimal a1 = new BigDecimal("0");
System.out.println(a1) //"0.0"

When I do

a1.pow(2)

I and print the value I get "0.00"
In my program, I loop this, and that causes problems because each time it loops, it doubles the trailing 0's. In order for my program to work as intended, it could get 2^100 trailing zeros which slows down performance and takes lots of memory. I have tried

a1.stripTrailingZeros();

but it still stores the useless zeros and takes a long time to compute.
In this, I need to maximize performance, so converting to a string and doing string manipulation might not be the best way. What should I do to fix this?


Solution

  • BigDecimal is immutable (and doesn't operate in place). Change

    a1.pow(2);
    

    to (something like)

    a1 = a1.pow(2);
    

    Of course, 0 * 0 is 0. So, to get a non-zero number; you could do something like

    public static void main(String[] args) {
        BigDecimal a1 = new BigDecimal("2");
        a1 = a1.pow(2);
        System.out.println(a1);
    }
    

    And I get (the expected)

    4