Replace loop with Long.numberOfTrailingZeros in BigDecimal(double val, MathContext mc) constructor

John Platts john_platts at hotmail.com
Mon Dec 22 00:02:13 UTC 2025


The following loop in the java.math.BigDecimal(double val, MathContext mc) constructor is inefficient:
        while ((significand & 1) == 0) { // i.e., significand is even
            significand >>= 1;
            exponent++;
        }

Here is a more efficient alternative using Long.numberOfTrailingZeros:
        final int numOfTrailingZerosInSignificand =
            Long.numberOfTrailingZeros(significand);
        significand >>= numOfTrailingZerosInSignificand;
        exponent += numOfTrailingZerosInSignificand;


More information about the core-libs-dev mailing list