0

I have been scratching my head at this VERY odd problem. I do some calculations in PHP and the end result is a number. This is a whole number, but because calculations are done, PHP considers this a float. However, when I typecast it as an integer, it magically gets subtracted one. As in 1. A whole integer down. I really am at a loss. Try for yourself.

<?php
$number_of_rows = 10;
$number_of_columns = 19;
$active = array();

$tile = 160;
$column = $tile/$number_of_columns; // 8.42105263158
$rounded_down = floor($column); // 8
$column = $column-$rounded_down; // 0.42105263158
$column = $column*$number_of_columns; // 8

var_dump($column); // 8 -> that is great
var_dump((int)$column); // 7 -> WTF?!!!

?>

PHP 7.0.12 on Linux 64 bit.

  • 1
    `echo serialize($column);` When you cast to `int` it doesn't round it truncates. – AbraCadaver Oct 21 '16 at 19:42
  • 1
    http://stackoverflow.com/questions/588004/is-floating-point-math-broken?rq=1 – AbraCadaver Oct 21 '16 at 19:45
  • The actual value of `$column` is probably something like `7.999999999999234`, which gets printed as `8` because of the default precision of printing. But when you cast it to `(int)`, the fraction is removed. – Barmar Oct 21 '16 at 19:50

1 Answers1

1

See the Warning in PHP manual for an explanation.

Excerpt that talks about precision and a floor() example:

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they 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.9999999999999991118....

c4n
  • 639
  • 1
  • 5
  • 11