Reputation: 151
$x = array(
"0",
"1689.60",
"0.00",
"-200",
"432.00",
"33.60"
);
$v = 0;
foreach($x as $p) {
$v += $p;
}
if($v == 1955.2) {
echo 'equal';
}
with this simple script I assumed that it will output "equal" but it didn't.
If I changed the value of -200 to -100 and changed the expected result value to 2055.2, it works just fine. I already solved my problem by type casting $v to string but I just want to find out why it didn't work if it's a numeric(integer or float) type.
Upvotes: 0
Views: 337
Reputation: 468
http://php.net/manual/en/language.types.float.php
The problem here is your floating values, even though they appear very equal, are not due to how PHP (and the computer itself) represents floating point integers. There are a few solutions in the comments on the source to testing floats for equality. I highly recommend going through that source; it's brief and informative.
Upvotes: 1