Variable Types and Maths - PHP
Currently working on a discount / special offer system and its not doing what i want it to!
I've got the price of a product pulling from a database. The field its stored in is a decimal(15,2) - so its deffinatly not stored as a string.
Code roughly goes as follows:
$price = $productItem['price'];
$percent_off = $specialItem['offer_value']);
$amount_off = $price / 100 * $percent_off;
$price = $price - $amount_off;
echo $price;
simple stuff aye. not exactly rocket science to work out what its doing.
All seems to work fine, except for a few products! One product has a price of 13.59 and is set to a 100% discount.
So, common sense tells me the calculation will be: discount will be ( 13.59 / 100 * 100 ) = 13.59 Price = 13.59 - 13.59 = 0
However, im getting: 1.78 as the returned value.
I've tried adding settype($price, "int"); and settype($price, "float"); etc etc and it still wont work. If i set the variable to integer then i loose all decimal places, and setting it to float gives me the same problem as above.
I'm a bit lost on this one… any suggestions from fellow programmers out there?
Well, the code is obviously simple, so it's hard to screw it up in any major way. For the discount calculation, I'd do:
price * discount / 100
…because it looks better and prevents any decimal drop-off. That's just me, though, and that's not really the solution to your problem, I'm sure.
Have you checked to make sure that the discount percentage that you're pulling is what you're expecting it to be? That seems to be the only part that you haven't verified (or maybe did and didn't mention it).
yeah all the values were deffinatly correct. i checked this over with another programmer at work and we came to the conclusion it was a variable "type" issue. i.e the values were being read as strings as opposed to float or integer etc.
this wasnt an issue i was prepared to spend 1/2 a day trying to solve, so i just stuck the extra IF in there and its fixed.
thanks for the suggestion though.
Mr_Cheese wrote: yeah all the values were deffinatly correct. i checked this over with another programmer at work and we came to the conclusion it was a variable "type" issue. i.e the values were being read as strings as opposed to float or integer etc.
Ahh, a type issue… well, I know you've probably already put it behind you, but I think the floatval function might've fixed it, then. I just assumed, like you, that the values were being read as their respective types. :happy: