Jump to content

[SOLVED] Simple equality check - driving me mad!


nickdrums

Recommended Posts

Hey all,

 

This is really driving me mad. I've got a script which gets invoked when someone buys something on my website. It integrates with Paypal, and essentially there is a check in the script to ensure that the shopping basket item price is the same as the price of the item in my product database. So, here is the code:

if($price * $quantity != $payment_amount) {
   error_mail("Item price (£$payment_amount) / quantity ($quantity) does not match database (£$price). Webshop record written anyway.");
}

To clarify, $price is read from a MySQL database (decimal(10,2)), and $quantity and $payment_amount are taken from a $_POST array sent by Paypal.

 

Now, pretty much every time a purchase is made, this condition is found to be TRUE, yet the error email confirms that the condition should have been false, e.g. $price might be 15.99, $quantity might be 1, and $payment_amount 15.99, but the condition is still TRUE.

 

I suspected that the problem might be an issue of variable types, so I tried adding (float) before each of the three variable names in the condition statement:

if((float)$price * (float)$quantity != (float)$payment_amount) {
   error_mail("Item price (£$payment_amount) / quantity ($quantity) does not match database (£$price). Webshop record written anyway.");
}

But this made no difference.

 

Can anyone save my sanity??

 

Nick.

When using floats it's possible that qty * price gives 15.9900000000000001, say, which is not equal to 15.99.

 

In this case, instead of testing for equality you need to check that the difference is so small as to be negligable.

 

if (abs($qty*$price - $amount) < 0.0001)
{
   // near enough, go ahead
}
else
{
   // error!
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.