user - 10 months ago 50

PHP Question

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.

Answer Source

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....