nickdrums Posted September 26, 2008 Share Posted September 26, 2008 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. Link to comment https://forums.phpfreaks.com/topic/125990-solved-simple-equality-check-driving-me-mad/ Share on other sites More sharing options...
Barand Posted September 26, 2008 Share Posted September 26, 2008 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! } Link to comment https://forums.phpfreaks.com/topic/125990-solved-simple-equality-check-driving-me-mad/#findComment-651553 Share on other sites More sharing options...
nickdrums Posted September 26, 2008 Author Share Posted September 26, 2008 OK thanks - I'll report back when I next get a sale! Link to comment https://forums.phpfreaks.com/topic/125990-solved-simple-equality-check-driving-me-mad/#findComment-651591 Share on other sites More sharing options...
nickdrums Posted September 27, 2008 Author Share Posted September 27, 2008 Yup - that seems to have done it - thanks a lot for your help. Nick. Link to comment https://forums.phpfreaks.com/topic/125990-solved-simple-equality-check-driving-me-mad/#findComment-651938 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.