开发者

subtracting a percentage from a value in 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 = "开发者_如何学JAVA25"; // 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.


How about this?

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


I'd go with

$newprice = $price - ($price * ($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


To get a percentage of a number you can just multiply by the decimal of the percent you want. For instance, if you want something to be 25% off you can multiply by .75 because you want it to cost 75% of it's original price. To implement this for your example you'd 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 this does is:

  1. Subtract the percentage discount from 100 to give us the percentage of the original price.
  2. Divide this number by 100 to give it to us in decimal (eg. 0.75).
  3. multiply the original price by the computed decimal above to get the new price.


$price -= ($percent == 'yes' ? ($price * ($amount / 100)) : $amount);


This might be helpful for the future.

For a better precision it is good to use the BCMath.

Example:

$newprice = bcsub($price, bcdiv(bcmul($price, $amount), '100');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜