php integer and float comparison mismatch

Notice the big red warning in the PHP Manual!

Never expect anything when comparing floats. The result of round, even if the precision is 0, is still a float. In your particular case it happened that the result was a little bigger than expected, so casting to int resulted in equality, but for other numbers it might as well happen for it to be a little smaller than expected and casting to int won’t round it, but truncate it, so you can’t use casting as a workaround. (As a note, a better solution than yours would be casting to string :), but still a lousy option.)

If you need to work with amounts of money always use the BC Math extension.

For rounding with BC Math you can use this technique:

$x = '211.9452';
$x = bcadd($x, '0.005', 2);

Good luck,
Alin

Leave a Comment