Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PHP typecasting behaving like this? (int) mis-rounding numbers?

Could someone please explain what is going on here?

echo (18.99 * 100); // output: 1899

echo (int)(18.99 * 100); // output: 1898

The only thing I can possibly think of is that the 1899 is actually 1898.999999999999 or something and PHP is converting it as part of echo somehow? If this is the case, why? If not, what is the reason for this strange behaviour?

like image 358
Eva Avatar asked Dec 24 '13 10:12

Eva


Video Answer


1 Answers

from manual:

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

Read here

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

in your case may be 18.99*100=1898.999999999999772626324556767940521240234375 so int truncated it to 1898.

like image 172
R R Avatar answered Nov 04 '22 11:11

R R