Subtracting percentage of value in php

I am writing something similar to the function of a coupon code and I want to be able to process both the set quantity codes and 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 looking for google when you read this looking for a solution, but I thought id would post it here to help others who might run into the same problem.

+4
source share
5 answers

How about this?

 $newprice = $price * ((100-$amount) / 100); 
+35
source

In addition to basic math, I also suggest that you use round () to force the result to have 2 decimal places.

 $newprice = round($price * ((100-$amount) / 100), 2); 

Thus, the price of $ 24.99, discounted by 25%, will be 18.7425, which is then rounded to 18.74

+5
source

I would go with

 $newprice = $price - ($price * ($amount/100)) 
+4
source

To get the percentage of the number, you can simply multiply by the decimal fraction of the percentage that you want. For example, if you want something to be 25% higher, you can multiply by 0.75 because you want it to cost 75% of its original price. To implement this for your example, you want to do something like:

 if($percent == "yes"){ $newprice = ($price * ((100-$amount) / 100)); // subtract $amount % of $price, from $price }else{ $newprice = $price - $amount; // if not a percentage, subtract from price outright } 

What it is:

  • Subtract a percentage discount of 100 to give us a percentage of the original price.
  • Divide this number by 100 to give it to us in decimal form (for example, 0.75).
  • Multiply the original price by the calculated decimal number above to get a new price.
+3
source
 $price -= ($percent == 'yes' ? ($price * ($amount / 100)) : $amount); 
+2
source

All Articles