Home » Php » php – Why would is_int(sqrt(100)) return false

# php – Why would is_int(sqrt(100)) return false

Posted by: admin July 12, 2020 Leave a comment

Questions:

Does anyone know why this always returns False?

``````is_int(sqrt(100))
``````

and what syntax should i use to check is square root is an integer ?

How to&Answers:

If you want to check whether a `sqrt` is an integer, you can do:

``````\$root = sqrt(\$val);

if((int) \$root == \$root)) {
// root is integer
}
``````

### Answer：

`sqrt` function returns `float` value, not `int`.

### Answer：

The problem here is in your definition of "integer". You’re reading it as "a value with no non-zero fractional significant figures", whereas in `is_int` it just refers to a datatype, i.e. literally anything with type `int`.

That is, the floating-point value `10.0` is still a floating-point value, even though its mathematical value is equal to that of the integer `10`.

The result of `sqrt` is never an integer; however, you can check whether a floating-point value has any non-zero fractional significant figures by comparing it to one in which you deliberately took them all off.

A naive implementation:

``````\$sqrt = sqrt(100);
if (\$sqrt == (int)\$sqrt) {
// ...
}
``````

However, of course you should never compare anything against a floating-point value with `==`; use your favourite floating-point equality mechanism to perform this test.

### Update

Actually, I suppose the only values for which this comparison could potentially fail are fractional, in which case the test should fail anyway. So `==` might be sufficient.

### Answer：

`sqrt` returns a float, not an integer, therefore `is_int` returns false.

Try use `is_float` instead.

### Answer：

is_int() refers to the datatype of the result, not to the value contained in that result. sqrt() always returns a result of datatype float, irrespective of the value

### Answer：

Data type of `sqrt(100) is float`. `is_int` checks for the data type not the `value`