I 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With