converting from float to Int in php -
this question has answer here:
- explain php output 1 answer
i trying understand converting float int in php ,and came across following code:
echo (int) ( (0.1+0.7) * 10 ); // echoes 7! my question why echo 7 instead of 8? logic behind it?
here:
$var = (int) $othervar; i guess:
$var = int($othervar); would work too. not!
gettype() tell type, get_class() tell class of object, both return strings, get_class() returns current class if no argument or null provided, if provide non-object get_class() it's sort of error.
these functions example of how bad php, gettype() , get_class(), fun fact, because have play "guess has underscore" have is_a() (function, expects $var , "typename") , instanceof (operator).
instead is:
$var = intval($othervar); and there's floatval, whole lot have val after them! more php sillyness.
note that:
$var = (string) $othervar; invokes $othervar's __tostring() method, there isn't __toint() method, strings.
hope helps.
addendum:
integers truncated, hence 7.
other addendum:
if want more controlled conversion can use round() works 1 expect, floor() (rounds down, 7 less x less 8 floors 7, -3 less x less-2 floors -3) , ceil() rounds (7 less x less 8 ceils 8, -3 less x less -2 ceils -2)
this question exact copy of:
why on earth php convert result of (int) ((0.1+0.7)*10) 7, not 8?
even example!
Comments
Post a Comment