Search code examples
mathdoublepowsqrtmath.sqrt

Detect if a double is a perfect square in Java


I want to detect if a double, like 6.25 is a perfect square or not.

To detect perfect squares for those numbers whose square root is an integer, I would do something like

public boolean isPerfectDouble( double i )
    {
        if (Double.isInfinite(i)) {
            return false;
        }
        double sqrt = Math.sqrt(i);
        return sqrt == Math.floor(sqrt) && sqrt*sqrt == i;
    }

However, this would not work for numbers like 6.25, which is indeed a perfect square.


Solution

  • First of all, you would need exact representation of such numbers. Probably you would want to truncate after certain decimal places. Then multiply the number by integer power of 100 until you get an integer. Check it the integer is square or not.