Home >Backend Development >PHP Tutorial >A brief discussion on PHP forced type conversion, use with caution!_PHP Tutorial
PHP is a weakly typed language. This is its advantage and feature, but sometimes you have to convert the type accordingly.
The problem comes at this time. Because in many cases, you will find that the data obtained after converting the type is quite different from the expected value.
Here I use forced conversion to integer as an example.
Looking at the code below, it can be said that it is absolutely impossible for you to tell the correct answer.
echo (int) 123.99999999999999;
echo (int) -1.999999999999999;
echo (int) -1.9999999999999999; 9999999999999;
echo (int) - 10.999999999999999;
echo (int) -1000.9999999999999;
echo (int) -9999999999;
First of all, I want to explain my system environment. win7 X86
The results obtained are as follows124
-1
-2
-1
-10
-1001
-1410065407
The official statement is:
When converting from a floating point number to an integer, it will be rounded towards zero.
If the floating point number is outside the integer range (usually +/- 2.15e+9 = 2^31), the result is undefined because there is not enough precision to make the float Points gives an exact integer result. There is no warning in this case, not even any notification!
Seeing this, you may think that the example I gave above is a bit far-fetched. Because it is simply impossible to use such high precision.
So, let’s look at the example below.
echo (int) ( (0.1+0.7) * 10 );
No need to guess, the execution result here is---7!Yes, you read it correctly and I typed it correctly. The result is 7 , not 8 as we usually think.
Now, you know how fucked up PHP is!
PHP official has this warning:
Never cast an unknown fraction to an integer, as this can sometimes lead to unpredictable results.
So be careful when performing forced type conversion! Large numerical values, high precision, and fractions should be used with caution!Of course, the above example can be handled this way.
x$num = (0.1 + 0.7) * 10;
echo (int) $num;