This question already has answers here:
Compare floats in php
(17 answers)
Closed 7 years ago.
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 ?
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:
http://phpfiddle.org/main/code/2hv5-n2fw
Related
This question already has answers here:
Checking that a value contains only digits, regex or no?
(3 answers)
Closed 2 years ago.
I need to check whether a variable contains integers only, and since PHP doesn't really care if numbers are represented in STRING type or not, I don't care either.
But when I use is_int() it returns false for '1' and when I use ctype_digit() it returns false for 1!
And is_numeric(), while accepting both string and float, accepts decimal numbers too.
I'm looking for a function that works like is_numeric() but doesn't accept decimals.
$var[] = 2;
$var[] = '2';
foreach($var as $key => $val){
if( ! is_int($val) && ! ctype_digit($val)) // <-- Any single function equivalent to these two checks?
return false;
}
P.S. I'm not lazy, but this has been bothering me for a long time that is_numeric() accepts string format numbers, but is_int() doesn't!
You can do a regex match to check if variable contains only integers using preg_match function
<?php
if(preg_match('/^\d+$/',$x) === 1){
// your code goes here
}
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 3 years ago.
the result of this should be zero!
echo array_sum([-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48]);
Why is giving -7.105427357601E-15?
Just try round(), you will get the same result.
echo round(array_sum([-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48]));
Because floating point values (which you have here when you use decimals) are not exact. They're approximations.
The error in that approximation comes out to -7.105427357601E-15 when summing these values.
It's because of floats. If you want to calculate something with precision 2 (for this example) you should use something like this:
$el = [-61.50,50.00,10.50,1.00,0.00,50.00,-16.73,-20.00,-55.75,42.48];
$sum = 0;
foreach ($el as $e) {
$sum += $e * 100;
}
echo $sum / 100;
You should never trust to float values. Another example from Javascript (Google developer Console):
This question already has answers here:
Checking if a variable is an integer in PHP
(14 answers)
php check to see if variable is integer
(12 answers)
Check if variable is a number and positive integer in PHP?
(6 answers)
Closed 4 years ago.
I know 0 is an integer, and
if((int)$some_data)
will return true(1) if the input is an integer and false(0) if not. I was trying to find whether 0 is a integer or not using a if condition, and the a simple example is here
$input= 0;
if((int)$input)
echo "Yes";
else
echo "No";
when I run this code, It returns "No", which means if condition returns 0 is not an integer. And I know that happens because
(int)0 returns 0
which means if(0) always returns false condition
so how can I find whether 0 is a integer or not. I don't know the question is duplicate or not, but I googled and still couldn't found a satisfying answer. If someone explain how to find whether 0 is int or not. Thanks in advance.
You have to use is_int()
if(is_int($input))
echo "Yes";
else
echo "No";
Note:- in your code you are doing casting, so it become if(0) which will always return false
The answer is pretty simple, but to understand why your code does not work you have to know that
(int)$input
is not a check, but is a cast. A cast is how we force a variable to be our desired variable type. So, basically you're saying to PHP "Hey PHP, no matter what is into $input, I want it to be an integer", PHP will try its best to force $input as an integer and, in your case, will return a 0.
Now, what happens if you try to do this
if (0)
simple, it will always be false.
Instead of casting $input use is_int()
is_int will check the type of the variable passed to it, but from your comments it seems like you're actually looking to test whether or not a string consists of digits. In that case, ctype_digit might be more useful:
$string = '0';
var_dump(ctype_digit($string));
bool(true)
https://3v4l.org/0j56h
i'm recommendation to use you with is_numeric
if (is_numeric(0)) { echo "Yes"; } else { echo "No"; }
// OUTPUT = YES
DEMO
Try This
$input= 0;
if(is_int($input))
echo "Yes";
else
echo "No";
This question already has answers here:
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 8 years ago.
When I run the follow code in PHP
if('yes' == 0)
echo 'a';
else
echo 'b';
The output is a.
I don't understand what happen?
And can I convert the php code to C source code to have a look what real happening?
PHP is a dynamically typed language, and == is a loose comparison operator, meaning it will first cast values it compares to one type, int for that matter, and then compare them; strings are being cast to integers by taking numericals from the left part, so 1abc casts to 1. By that logic yes cast to 0, and 0 == 0 yields true.
This question already has an answer here:
explain php output
(1 answer)
Closed 9 years ago.
I am trying to understand converting from a float to an int in PHP ,and came across the following code:
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
My question is why does it echo 7 instead of 8? What is the logic behind it?
Here:
$var = (int) $othervar;
I would guess:
$var = int($othervar);
would work too. BUT IT DOES NOT!
gettype() will tell you the type, get_class() will tell you the class of an object, both return strings, get_class() returns the current class if no argument or null is provided, if you provide a non-object to get_class() it's some sort of error.
These functions are an example of how bad php, gettype() and get_class(), fun fact, because you have to play "guess which has an underscore" you also have is_a() (function, expects $var and "typename") and instanceof (operator).
Instead it is:
$var = intval($othervar);
and there's floatval, the whole lot have val after them! More PHP sillyness.
Note that:
$var = (string) $othervar;
invokes $othervar's __toString() method, but there isn't a __toInt() method, just strings.
Hope this helps.
Addendum:
Integers are always truncated, hence 7.
Other addendum:
If you want more controlled conversion you can use round() which works as one would expect, floor() (rounds down, so 7 less x less 8 floors to 7, -3 less x less-2 floors to -3) and ceil() which rounds up (7 less x less 8 ceils to 8, -3 less x less -2 ceils to -2)
This question is an almost exact copy of:
Why would on earth PHP convert the result of (int) ((0.1+0.7)*10) to 7, not 8?
Even the example!
Because the actual value stored in memory is something like 7.999999999999999999999999 which is caused by rounding error.
you can also use intval()
$float = 7.99999999999999999999999999999999;
$int = intval($float);
echo $int;