Why is_int (sqrt (100)) returns false

Does anyone know why this always returns False?

is_int(sqrt(100)) 

and what syntax should I use to check if the square root is integer?

+7
source share
6 answers

If you want to check if sqrt an integer, you can do:

 $root = sqrt($val); if((int) $root == $root)) { // root is integer } 
+3
source

sqrt returns a float , not an int .

+10
source

The problem here is in your definition of "whole." You read it as "a value without non-zero fractional significant digits", whereas in is_int it simply refers to a data type, that is, literally everything with an int type.

That is, a floating point value of 10.0 is still a floating point value, although its mathematical value is equal to the value of the integer 10 .

The result of sqrt never an integer; however, you can check if any nonzero fractional significant digits are floating point values ​​by comparing them to the one in which you deliberately took everything away.

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 favorite floating point equality mechanism to perform this test.

Update

In fact, I believe that the only values ​​for which this comparison could potentially fail are fractional, in which case the test should still fail. Therefore == may be enough.

+6
source

sqrt returns a float, not an integer, so is_int returns false.

Try instead of is_float .

+2
source

is_int () refers to the data type of the result, not the value contained in this result. sqrt () always returns the result of a data type float, regardless of the value

+1
source

sqrt(100) is float data sqrt(100) is float . is_int checks data type, not value

-one
source

All Articles