December 9, 2010

[SOLVED] PHP: Why 2 !=2 aka "never compare floating point numbers for equality"

“never compare floating point numbers for equality”.

The reason (19.6*100) !== (double)1960, is because inside a computer they are not equal.

Try this:

<?php

printf("%.15f", (19.6*100));

?>

Outputs: 1960.000000000000227 (not 1960 as somewhat expected)

If comparison is required a few options come to mind (other than BCMath):

1) Round numbers before comparison:

<?php

$sig_figs = 5;
echo (round((19.6*100), $sig_figs) !== round((double)1960, $sig_figs)) ? 'not equal' : 'equal';

?>

Outputs: equal

Source: php.net

No comments:

Post a Comment