Today i saw surpring bug in php on data type conversion. We know php is loosely typed lagnuage , that we can convert a datatype to another datatype unlike C, Java. I tried to convert a float value to integer value but it outputs a wrong result…
I wonder why it happens. The code is below
echo (int) ((0.7+0.1)*10);
It’s expected to show 8 but it shows 7. It’s hard to find the problem. Then i googled this problem and found, the result of this simple arithmetic
expression is stored internally as 7.999999 instead of 8; when the value is converted to int, PHP simply truncates away the fractional part, resulting in a rather significant error (12.5%, to be exact). So experts suggested to use BCMath extension instead of PHP’s built-in data types.