PHP is a weak language. This is its advantage and feature, but sometimes you have to convert the type accordingly.
This is the case. In many cases, you will find that the data obtained after the conversion type is significantly different from the expected value.
Here I use forced conversion to integer as an example.
Looking at the code below, we can say that you cannot say the correct answer.
Echo (int) 123.999999999999999;
Echo (int)-1.999999999999999;
Echo (int)-1.9999999999999999;
Echo (int)-0.99999999999999999;
Echo (int)-10.999999999999999;
Echo (int)-1000.9999999999999;
Echo (int)-9999999999;
Next let's take a look at the results I got.
First, describe my system environment. Win7 X86
The result is as follows:
124
-1
-2
-1
-10
-1001
-1410065407
The official statement is:
When the value is converted from a floating point to an integer, It is rounded to zero.
If the floating point number exceeds the Integer Range (usually +/-2.15e + 9 = 2 ^ 31), the result is uncertain, because there is not enough precision to make the floating point number give an exact integer result. In this case, there is no warning or even no notification!
After talking so much about it, I would like to sum up one sentence: precision is not enough for me!
Here, you may think that the example above is a little far-fetched. Because it is impossible to use that high precision.
Let's look at the example below.
Echo (int) (0.1 + 0.7) * 10 );
You don't have to guess. Here the execution result is --- 7!
Yes, you are not mistaken. I didn't make a mistake either. The result is 7 instead of 8.
Now, you know how crazy PHP is!
PHP has the following warning:
Never forcibly convert an unknown score to an integer, which sometimes leads to unexpected results.
Therefore, be cautious when performing forced type conversion! Large values, high precision, and scores must be used with caution!
Of course, the above example can be processed in this way.
X $ num = (0.1 + 0.7) * 10;
Echo (int) $ num;