Why does this code print the result "7"?
I recently started learning 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
Typically, simple decimal fractions, such as 0.1 or 0.7, cannot be converted to their internal binary copies without a slight loss of precision. 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.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 example, 1/3 in decimal becomes 0.3.
You are using floating point inaccuracy.
0.1 + 0.7 is not exactly 0.8, but slightly less. A cast to int just truncates the value and gives a result of 7.
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
Characteristically, simple decimal fractions, such as 0.1 or 0.7, cannot be converted to their internal binary counterparties without a slight loss of accuracy. This can lead to confusing results: for example, gender ((0,1 + 0,7) * 10) usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.
As others have said, this is due to a loss of accuracy, as evidenced 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 probably see a floating point rounding error, and when you int() it goes from 7 ... 9 to 7.
I'm not sure, but this is probably because the int cast is truncated.
.1 +.7 may result in an error .79999999999999999999999999 and
multiplying this by 10 = 7.9999999999999999999
(int) truncates this value to 7.