Came across a rather “interesting” peculiarity in PHP, which affects mathematical operations involving floating point numbers. Before getting into the details, let me introduce you to the problem I was trying to help a friend solve. The goal was to take an arbitrary floating point number, let’s say 1.841243, and convert it to a whole number where decimal points became part of the whole, so 1.8432432 would become 18432432. The first solution was a very simple scriptlet, which if C has taught us anything should’ve worked.

PHP:

<?php

$a = 1.8432432;

while ((int)$a != $a) $a *= 10;

?>

This code relies on 2 premises, which are true in PHP:

1) Casting a float to an int, results in a drop of decimal points. (Ex. (int) 1.8432432 => 1)

2) By multiplying value by 10, all decimal places will eventually be gone and (float)$a will equal (int)$a.

While both premises are true, the above code does not work, in fact, it results an unterminated loop, YIKES!

Continue reading "PHP & Floating Point Math"