Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtracting a percentage from a value in php

Tags:

php

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.

like image 615
mrpatg Avatar asked Dec 08 '09 02:12

mrpatg


People also ask

How can I get percentage in PHP?

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.

How can we calculate percentage?

To determine the percentage, we have to divide the value by the total value and then multiply the resultant by 100.


2 Answers

How about this?

$newprice = $price * ((100-$amount) / 100);
like image 149
Amber Avatar answered Oct 14 '22 03:10

Amber


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

like image 35
Paul Dixon Avatar answered Oct 14 '22 01:10

Paul Dixon