php 从php中的值中减去一个百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1864291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
subtracting a percentage from a value in php
提问by mrpatg
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.
我在您阅读本文时搜索谷歌寻找解决方案,但我认为我也将其发布在这里以帮助可能遇到相同问题的其他人。
回答by Amber
How about this?
这个怎么样?
$newprice = $price * ((100-$amount) / 100);
回答by Tim Lytle
I'd go with
我愿意
$newprice = $price - ($price * ($amount/100))
回答by Jeremy Logan
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:
要获得一个数字的百分比,您只需乘以您想要的百分比的小数即可。例如,如果您希望某件商品享受 25% 的折扣,您可以乘以 0.75,因为您希望它的价格为原价的 75%。要为您的示例实现这一点,您需要执行以下操作:
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:
它的作用是:
- Subtract the percentage discount from 100 to give us the percentage of the original price.
- Divide this number by 100 to give it to us in decimal (eg. 0.75).
- multiply the original price by the computed decimal above to get the new price.
- 从 100 中减去折扣百分比得到原始价格的百分比。
- 将此数字除以 100 以十进制形式提供给我们(例如 0.75)。
- 将原始价格乘以上面计算的小数点以获得新价格。
回答by Paul Dixon
In addition to the basic mathematics, I would also suggest you consider using round()to force the result to have 2 decimal places.
除了基本的数学,我还建议你考虑使用round()来强制结果有 2 个小数位。
$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
这样,24.99 美元的价格折现 25% 将产生 18.7425,然后四舍五入为 18.74
回答by wpjmurray
$price -= ($percent == 'yes' ? ($price * ($amount / 100)) : $amount);

