在PHP中累计价格

时间:2017-03-06 05:46:20

标签: php magento-1.9

我想用PHP汇总价格

e.g。我的价格是£74.31我要舍入到最接近的74.35或者如果高于£74.36那么£74.40以及小数我总是希望以5结束0

例如

£74.31 would be round up to £74.35
£74.32 would be round up to £74.35
£74.33 would be round up to £74.35
£74.34 would be round up to £74.35
£74.35 would be round up to £74.35

£74.36 would be round up to £74.40
£74.37 would be round up to £74.40
£74.38 would be round up to £74.40
£74.39 would be round up to £74.40
£74.40 would be round up to £74.40

我试图用下面的价格来计算价格

round(($price * $rate) * 2, 1)/2;

3 个答案:

答案 0 :(得分:1)

你也可以试试这个逻辑,

<?php
    $x = 74.31;
    $number = $x*100;
    if($number % 5){
      $number = $number + 5 - ($number % 5);
    }else{
      $number = $number - ($number % 5);
    }
    $number /=100;
    echo number_format((float)$number, 2, '.', '');
?>

现场演示:https://eval.in/748595

答案 1 :(得分:1)

希望这是有道理的,但如果它没有一些快速背景:

你发布的round($number * 2) / 2有效,因为任何一个都有两半。如果你想要四舍五入到季度,你会使用round($number * 4)/4,而五分之一将是round($number * 5)/5。等等。

因为看起来好像想要舍入到最近的镍,一美元就有20个镍币。问题是它愿意上下移动。同样的事情发生在使用ceil(),但它只会向上移动,这似乎是你想要的。

function round_to_nickel($item, $decimals=false){
    $num = ceil($item * 20) / 20;
    return ($decimals) ? number_format($num, (int)$decimals) : $num;
}

希望它有所帮助!

答案 2 :(得分:0)

根据您的要求使用php floor()和ceil()以及round()函数