Reputation: 37
I have a strange bug when multiplying decimals. When I multiply a decimal such as 2.1 by a number such as 2 (to get the product 4.2), PHP displays them identically, and, on comparison, shows them as equal. But when I multiply 2.1 by 7 (14.7), though PHP still displays them as equal, upon comparison it declares the products unequal.
Here's code illustrating the issue (note what PHP returns):
$num_1 = 4.2;
$num_2 = 2.1*2;
if($num_1 == $num_2){
$eq = "Equal";
}else{
$eq = "Unequal";
}
echo $num_1.", ".$num_2.", ".$eq."<br>";
// Returns 4.2, 4.2, Equal
$num_1 = 14.7;
$num_2 = 2.1*7;
if($num_1 == $num_2){
$eq = "Equal";
}else{
$eq = "Unequal";
}
echo $num_1.", ".$num_2.", ".$eq."<br>";
// Returns 14.7, 14.7, Unequal
Thanks.
Upvotes: 1
Views: 8409
Reputation: 12039
I suggest you to use round()
.
$num_1 = round(14.7, 2);
$num_2 = round(2.1 * 7, 2);
echo ($num_1 == $num_2) ? 'equal' : 'uequal';
Now notice the result here what exactly occurred.
$num_1 = 14.7;
$num_2 = 2.1 * 7;
echo abs($num_1-$num_2); //Output: 1.7763568394003E-15
Upvotes: 1
Reputation: 440
This is PHP, bro! Just convert your floats to strings and compare them...
$num_1 = 14.7;
$num_2 = 2.1*7;
if((string) $num_1 == (string) $num_2){
$eq = "Equal";
}else{
$eq = "Unequal";
}
echo $num_1.", ".$num_2.", ".$eq."<br>";
Or use that bcmul
as shown above...
Upvotes: -1
Reputation: 31614
The problem is that some floating point numbers can't be represented accurately. If you need to compare them, or a higher level of precision, use bcmul
$num_1 = 14.7;
$num_2 = bcmul(2.1, 7, 1);
if((string)$num_1 == $num_2){
$eq = "Equal";
}else{
$eq = "Unequal";
}
echo $num_1.", ".$num_2.", ".$eq."<br>";
Upvotes: 2