PHP is a weak language. This is its advantage and feature, but sometimes you have to convert the type accordingly.
The problem arises at this time. Because in many cases, you will find that the data obtained after converting the type is much different from the expected value.
Here I use cast to plastic surgery as an example.
Looking at the code below, you can say that you will never be able to give 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;
Let’s take a look at the results I got.
First, I need to explain my system environment. win7 X86
The results obtained are as follows
124
-1
-2
-1
-10
-1001
-1410065407
The official statement is:
When converted from a floating point number to an integer, it will be rounded to zero.
If the floating point number is outside the integer range (usually +/- 2.15e+9 = 2^31), the result is uncertain because there is not enough precision for the floating point number to give an exact integer result. There is no warning or even any notification in this case!
After saying so much, I can only sum it up in one sentence: Not accurate enough has something to do with me!
Seeing this, you may think the example I gave above is a bit far-fetched. Because it is impossible to use such high accuracy.
So, let's take a 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 right, and I didn't hit it wrong, and the result is 7, not 8 as we usually think.
PHP official warns:
Never cast unknown scores to integers, which can sometimes lead to unpredictable results.
Therefore, be careful when performing cast type conversion! Use large numbers, high precision, and carefully with scores!
Of course, the example above can be handled like this.
x$num = (0.1 + 0.7) * 10;
echo (int) $num;