PHP cast to integer returns wrong value

不羁的心 提交于 2019-12-13 08:39:19

问题


Have a look at this my friend and tell me I'm not crazy...

echo (int) (9.45 * 100); // gives 944
echo (int) 945; // gives 945

I don't understand why the first instruction would return 944!???? Is this a known php issue? help is appreciated as always!


回答1:


According to PHP documentation (http://php.net/manual/en/language.types.integer.php)

When converting from float to integer, the number will be rounded towards zero. 

That's why you are getting 944.




回答2:


Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision.

This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.

for more information you can check at http://php.net/manual/en/language.types.float.php



来源:https://stackoverflow.com/questions/18106783/php-cast-to-integer-returns-wrong-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!