Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 449
L.Lawliet Avatar asked Jun 30 '10 15:06

L.Lawliet


3 Answers

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.

like image 101
James Goodwin Avatar answered Sep 28 '22 00:09

James Goodwin


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 ); 
?>
like image 33
Dirk Vollmar Avatar answered Sep 27 '22 23:09

Dirk Vollmar


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.

like image 31
Anthony Potts Avatar answered Sep 27 '22 22:09

Anthony Potts