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?
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;