What is strange is that the running the script with the following values prints “It worked!!!”
$foo1 = 2.8.;
$foo2 = 3.13;
$expected = 5.93;
This also works -
$foo1 = 2.85;
$foo2 = 3.1;
$expected = 5.95;
This could be an issue with my install of PHP. I’m running the default dotdeb (PHP 5.2.0 with suhoshin patch) install on Debian Sarge.
OR maybe I’m just too tired
I also searched the PHP Bug database but couldn’t find anything
So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.
im gonna have to test this, but surely that calculation would work if you place quotes around the $foo1 $foo2 and $expected values??
i apologise in advance if im wrong
im gonna have to test this, but surely that calculation would work if you place quotes around the $foo1 $foo2 and $expected values??
i apologise in advance if im wrong
No, not necessarily. Floating point numbers are dealt with differently depending upon CPU. This becomes extremely more apparent the more places you have to the right of the point. Making the number a string doesn’t change the fact that PHP calculated it to be a different value to what you expected.
This is something that must be taken into consideration when writing code to be used across platforms since all platforms will give different results. Interestingly, Java doesn’t suffer this cross-platform problem since the VM actually does some of the math, not just the CPU - with the HUGE drawback of being hundreds of times slower at doing math with floating point numbers.