开发者

Since when does PHP autocast integer to float?

开发者 https://www.devze.com 2023-01-04 21:45 出处:网络
echo 1/3; I was expecting the above to output 0, but in fact PHP is smart enough to output 0.33333333333333
echo 1/3;

I was expecting the above to output 0, but in fact PHP is smart enough to output 0.33333333333333

Since开发者_JAVA百科 when does PHP start to behave like this?


It has always behaved like this. See: http://php.net/manual/en/language.operators.arithmetic.php

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.


PHP isn't a strongly typed language. It does things like that all the time.

As far as I know, php was designed like this from the beginning.


I'd say this is the expected behaviour.

If you want an integer, force a cast:

echo (int)(1/3);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号