This question already has an answer here:
I was working on a code and I could not understand the weird result I was getting.
<?php
$a = 0.01;
$p = pow(0.1, 2); // result: 0.01
if( $a < $p ){
echo "true";
}
?>
The result of this condition is always "true" while both of the variables have same value, but the result coming from pow
is changing something internally. Seems like I would not be able to rely on this function. Would someone please help me figuring this out ?
</div>
its because of float inaccuracy, take a look at answered question mentioned in comment by b0s3
Read the red warning first http://www.php.net/manual/en/language.types.float.php. You must never compare floats for equality. You should use the epsilon technique.
For example:
if (abs($a-$b) < EPSILON) { … }
where EPSILON is constant representing a very small number (you have to define it)
https://stackoverflow.com/a/3149007/4998045
so you can trust pow
function but you cant trust float comparsion
PHP Docs said:
base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.
Maybe you need to convert all to int or all to float.
if( (float)$a < (float)$p ){
echo "true";
}
See it run: