开发者

Why does this code print a result of '7'?

I 开发者_JS百科recently start to learn PHP.

   <?php
    echo (int) ( (0.1+0.7) * 10 ); // prints '7', why not '8' ?
    ?>

Please convince me of this type-conversion process.


From PHP.net

It is typical that simple decimal fractions like 0.1 or 0.7 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.9.

This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.


You are running into floating point inaccuracy.

0.1 + 0.7 is not exactly 0.8, but slightly less. The cast to int simply truncates the value and yields 7 as the result.

To get the correct result use rounding:

<?php
    echo (int) round( (0.1+0.7) * 10 ); 
?>


From http://php.net/manual/en/language.types.float.php

It is typical that simple decimal fractions like 0.1 or 0.7 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.9.


As others have said, it's due to a loss of precision, as revealed by:

<?php
printf("%30.27f\n", (0.1 + 0.7) );
printf("%d\n", (int) (0.1 + 0.7) );
printf("%30.27f\n",  ( (0.1+0.7) * 10 ) );
printf("%d\n", (int) ((0.1 + 0.7) * 10) );
?>

which outputs:

0.799999999999999933386618522
0
7.999999999999999111821580300
7


You're probably seeing a floating point rounding error, and when you int() it, it goes from being 7...9 to 7.


I am not sure, but this is probably because the int cast is truncating.

.1 + .7 might result in .799999999999999999999999 and

multiplying this by 10 = 7.9999999999999999999

(int) truncates this to 7.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜