Discussion on PHP mandatory type conversion caution!

  • 2020-06-07 04:05:31
  • OfStack

PHP is a weakly typed language. This is the advantage and characteristic, but sometimes you have to convert the type accordingly.

That's where the problem comes in. Because in many cases, you will find that the data you get after converting the type is about a fraction of a second from the expected value.

Here I use the example of conversion to plastic.

Looking at the code below, it's safe to say that you'll never get the right 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;

So let's see what I get.

First of all, I want to explain my system environment. win7 X86

The results are as follows

124
-1
-2
-1
-10
-1001
-1410065407

The official line is:

When converted from a floating-point number to an integer, the integer is rounded to zero.

If the float exceeds the integer range (usually +/ -2.15 e+9 = 2^31), the result is uncertain because there is not enough precision for the float to give an exact integer result. No warning or even any notice in this case!

Said so much, sum up on 1 sentence: precision is not enough related to my bird matter!

Looking at this, you might think my example above is a little far-fetched. Because it's simply not possible to use that kind of precision.

So, let's look at the following example.

echo (int) ( (0.1+0.7) * 10 );

Don't guess, the execution result here is --7!

Yeah, you read that right, and I typed it right, so it's 7, not 8 as we usually think.

Now you know how fucked PHP is!

The PHP official has this warning:

Never cast an unknown score to integer, as this can sometimes lead to unpredictable results.

So be careful when casting! Large value, high precision, fractions should be used with caution!

Of course, the above example can be treated like this.
x$num = (0.1 + 0.7) * 10;
echo (int) $num;


Related articles: