Search code examples
phpsqrt

Square root in PHP


Why is the output of sqrt not an integer for "16" in PHP?

Example

php > $fig = 16;
php > $sq = sqrt($fig); //should be 4
php > echo $sq;
4
php > echo is_int($sq);            // should give 1, but gives false
php > 

I feel that the problem is in the internal presentation which PHP hides similarly as Python. How can you then know when the given figure is integer after taking a square root?

So how can you differentiate between 4 and 4.12323 in PHP without using a regex?


Solution

  • According to the PHP manual, float sqrt ( float $arg ), sqrt() always returns a float. Using the is_int() function won't solve the problem because it checks the datatype and returns a failure.

    To get around this, you can test it by using modulus instead: (must be fmod() for floating point modulus and not the % operator for integer modulus)

    if (fmod(sqrt(16), 1) == 0) {
       // is an integer
    }
    

    If you are using PHP 5.2.0 or later, I believe this would also work, but I haven't used it in this type of circumstance to be certain:

    $result = sqrt(16);
    if (filter_var($result, FILTER_VALIDATE_INT)) {
        // is an integer
    }