0

I don't know if this is a bug or expected behavior, but the following unit test passes against all logic:

public function testPHPIsBroken()
{
    $this->assertEquals((int)(2.04 * 100), (int)(2.05 * 100));
}

This is using PHP 5.4.7. Is there something obvious about how decimal numbers work that I should know as a programmer in order to avoid this. Currently all monetary values in my project are set like this, which could result in some serious egg on my face...

  • Save all money related stuff as the lowest possible denomination. Meaning, 1 dollar is not A dollar, it's 100 cents. – Andrei Apr 24 '15 at 13:01
  • And you realize they both return `204`, which is the same, floating points and all ! – adeneo Apr 24 '15 at 13:04
  • 2
    it has to do with floating point precision. consider using [bcmath](http://php.net/manual/en/book.bc.php) for comparing floats. – Jonathan Apr 24 '15 at 13:04
  • `echo (int)(2.05 * 100);` echos 204, while `echo (2.05 * 100);` echos 205. Does it not evaluate and then cast to an integer? – enigma Apr 24 '15 at 13:07
  • 2
    This is something that every programmer working with almost every programming language should know.... ___especially___ if they're working with monetary values – Mark Baker Apr 24 '15 at 13:14

0 Answers0