我将此代码用于计算价格getPrecio
。
对于价格低于1的产品(例如0.2或0.02),此功能不起作用。
为什么?
这是代码:
function getPrecio($p)
{
if($p > 0 && $p <= 1) return $p*1.99;
}
它是一个PHP代码。 当我说这不起作用时,它不会更正计算出的价格。
试试这个而不是计算
function getPrecio($p)
{
$floatPrice = floatval($p);
if($floatPrice > 0 && $floatPrice <= 1) return $floatPrice *1.99;
//if($p > 0 && $p <= 1) return $p*1.99;
elseif($p > 1 && $p <= 3) return $p*1.95;
更新代码
function getPrecio($p)
{
$floatPrice = floatval($p);
$floatCalculatedResult = 0;
if (between($floatPrice, 0, 1)) {
$floatCalculatedResult = $floatPrice * 1.99;
} else if (between($floatPrice, 1, 3)) {
$floatCalculatedResult = $floatPrice * 1.95;
} else if (between($floatPrice, 3, 5)) {
$floatCalculatedResult = $floatPrice * 1.90;
} else if (between($floatPrice, 5, 10)) {
$floatCalculatedResult = $floatPrice * 1.70;
} else if (between($floatPrice, 10, 20)) {
$floatCalculatedResult = $floatPrice * 1.60;
} else if (between($floatPrice, 20, 30)) {
$floatCalculatedResult = $floatPrice * 1.56;
} else if (between($floatPrice, 30, 50)) {
$floatCalculatedResult = $floatPrice * 1.52;
} else if (between($floatPrice, 50, 80)) {
$floatCalculatedResult = $floatPrice * 1.49;
} else if (between($floatPrice, 80, 100)) {
$floatCalculatedResult = $floatPrice * 1.45;
} else if (between($floatPrice, 100, 130)) {
$floatCalculatedResult = $floatPrice * 1.40;
} else if (between($floatPrice, 130, 200)) {
$floatCalculatedResult = $floatPrice * 1.39;
} else if (between($floatPrice, 200, 250)) {
$floatCalculatedResult = $floatPrice * 1.35;
} else if (between($floatPrice,250, 500)) {
$floatCalculatedResult = $floatPrice * 1.32;
} else if (between($floatPrice, 500, 700)) {
$floatCalculatedResult = $floatPrice * 1.28;
} else if (between($floatPrice, 700, 900)) {
$floatCalculatedResult = $floatPrice * 1.26;
} else if (between($floatPrice, 900, 1000)) {
$floatCalculatedResult = $floatPrice * 1.25;
} else if (between($floatPrice, 1000, 10000)) {
$floatCalculatedResult = $floatPrice * 1.15;
}
return $floatCalculatedResult;
}
function between($var, $from, $to)
{
return ($var > $from && $var <= $to);
}
更新,如果更改字段为0,02到0.02代码的字段工作。但需要正确的代码才能使用0,02
答案 0 :(得分:1)
也许$p
被转换为int,所以0.2或0.02只是0.尝试使用floatval($p)
function getPrecio($p)
{
$floatPrice = floatval($p);
if($floatPrice > 0 && $floatPrice <= 1) return $floatPrice *1.99;
}
更新回答
这应该按预期工作。
function getPrecio($p)
{
$floatPrice = floatval($p);
$floatCalculatedResult = 0;
if (between($floatPrice, 0, 1)) {
$floatCalculatedResult = $floatPrice * 1.99;
} else if (between($floatPrice, 1, 3)) {
$floatCalculatedResult = $floatPrice * 1.95;
}
return $floatCalculatedResult;
}
function between($var, $from, $to)
{
return ($var > $from && $var <= $to);
}
您可以继续使用between
功能
答案 1 :(得分:0)
在顶部添加:
$p = floatval(str_replace(',', '.', $p));
这会将0,02
更改为0.02
。