Im writing something similar to a coupon code function, and want to be able to handle both set amount codes, as well as percentage amounts.
My code is as follows;
$amount = "25"; // amount of discount
$percent = "yes"; // whether coupon is (yes) a percentage, or (no) a flat amount
if($percent == "yes"){
$newprice = ???????; // subtract $amount % of $price, from $price
}else{
$newprice = $price - $amount; // if not a percentage, subtract from price outright
}
Im searching google as you read this looking for a solution but i thought id post it here as well to help others who may encounter same problem.
Divide $percentage by 100 and multiply to $totalWidth . Simple maths. in case the type is an integer it is better if you multiply first, then divide by 100. Example when dividing first: int answer = 50/100 = 0.5 (int rounds 0.5 to 1); answer*width = 1*350 = 350.
To determine the percentage, we have to divide the value by the total value and then multiply the resultant by 100.
How about this?
$newprice = $price * ((100-$amount) / 100);
In addition to the basic mathematics, I would also suggest you consider using round() to force the result to have 2 decimal places.
$newprice = round($price * ((100-$amount) / 100), 2);
In this way, a $price of 24.99 discounted by 25% will produce 18.7425, which is then rounded to 18.74
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With