PHP casting float to int returns another value

When I execute the following code in PHP (v5.5.9), something unexpected will happen:

$valueAsCents = 54780 / 100 * 100; var_dump($valueAsCents); var_dump((int) $valueAsCents); 

It returns

 float 54780 int 54779 

So, apparently, the float value without decimals is not equal to the int value. Any ideas on what's going on here?

+6
source share
1 answer

When you divide $ valueAsCents = 54780/100, then it becomes floating, which is not always digitally accurate due to how they are stored. In my tests, I got 547.7999999999999545252649113535881042480468750000

When multiplied by 100, it will be 54779.99999999999927240423858165740966796870000

When PHP goes to int, it always rounds down.
When converting from float to integer, the number will be rounded to zero.

This is why the int value is 54779

In addition, the PHP manual for the float type also provides a hint that floating point numbers may not do what you expect.

In addition, rational numbers that are accurately represented as floating point numbers in base 10, such as 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which are used internally, regardless of the size of the mantissa Therefore, they cannot be converted to their internal binary copies without a slight loss of accuracy. This can lead to confusing results: for example, gender ((0,1 + 0,7) * 10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118 ....

+3
source

All Articles