Why does PHP modeling look like this? (int) incorrect rounding of numbers?

Can someone explain what is going on here?

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

The only thing I can think of is that 1899 is actually 1898.999999999999 or something else, and does PHP somehow turn it as part of echo ? If so, why? If not, what is the reason for this strange behavior?

+7
php rounding
source share
1 answer

from the manual:

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

If the float is outside the 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 float does not have enough precision to get an accurate integer result. No warning, even if the notification is not published, it will happen!

Attention

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

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

Read here

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, the gender ((0,1 + 0,7) * 10) usually returns 7 instead of the expected 8 , since the internal representation will be something like 7.9999999999999991118 ....

in your case it could be 18.99*100=1898.999999999999772626324556767940521240234375 , so int truncates it to 1898.

+5
source share

All Articles