从php中的值减去一个百分比

mrp*_*atg 6 php

我写的东西类似于优惠券代码功能,并希望能够处理设定金额代码和百分比金额.

我的代码如下;

$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
}
Run Code Online (Sandbox Code Playgroud)

我正在搜索谷歌,因为你正在阅读这个寻找解决方案但我想在这里发布它也可以帮助其他可能遇到同样问题的人.

Amb*_*ber 41

这个怎么样?

$newprice = $price * ((100-$amount) / 100);
Run Code Online (Sandbox Code Playgroud)


Pau*_*xon 8

除了基本的数学,我还建议你考虑使用round()来强制结果有 2 个小数位。

$newprice = round($price * ((100-$amount) / 100), 2);
Run Code Online (Sandbox Code Playgroud)

这样,24.99 美元的价格折现 25% 将产生 18.7425,然后四舍五入为 18.74


Tim*_*tle 5

我会去的

$newprice = $price - ($price * ($amount/100))
Run Code Online (Sandbox Code Playgroud)


Jer*_*gan 5

要获得一个数字的百分比,您只需乘以您想要的百分比的小数即可。例如,如果您希望某件商品享受 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
}
Run Code Online (Sandbox Code Playgroud)

它的作用是:

  1. 从 100 中减去折扣百分比得到原始价格的百分比。
  2. 将此数字除以 100 以十进制形式提供给我们(例如 0.75)。
  3. 将原始价格乘以上面计算的小数点以获得新价格。