Daily Archives: November 12, 2014

PHP floats are not created equal

I was given a bug report today and after digging into the problem I found that two floating point numbers that appeared to be equal were not.

Here is a little code and the output. At the bottom is the actual value of each.


if($paymentAmount > $amountDue) {
echo 'is greater';
} else {
echo 'equal or less';
printf("%.40f\n", $paymentAmount) . ' ';
printf("%.40f\n", $amountDue)

is greater

PHP acknowledges the issues here under “comparing floats” http://php.net/manual/en/language.types.float.php

The PHP website provides a way to test the number for equality by limiting them to 5 decimals –

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$a and $b are equal to 5 digits of precision.

$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
    echo "true";