四舍五入到最近的50美分

Jim*_*Jim 11 php rounding

我有以下代码将我的金额四舍五入到最近的美元:

    switch ($amazonResult['SalesRank']) {
    case ($amazonResult['SalesRank'] < 1 || trim($amazonResult['SalesRank'])===''|| !isset($amazonResult['SalesRank']) || $amazonResult['SalesRank']=== null):
        $Price=((float) $lowestAmazonPrice) * 0.05;
        $payPrice = round($Price, 0);  //to round the price up or down to the nearest $
        break; 
    case ($amazonResult['SalesRank'] > 0 && $amazonResult['SalesRank'] <= 15000):
        $Price=((float) $lowestAmazonPrice) * 0.20;
        $payPrice = round($Price, 0);  //to round the price up or down to the nearest $
        break;
Run Code Online (Sandbox Code Playgroud)

我明白,如果我使用圆形($ Price,2); 我将有2位小数,但是有没有办法舍入到最接近的50美分?

Pal*_*ium 24

一些简单的数学应该可以解决问题.而不是四舍五入到最接近的50美分,圆形加倍$price到最接近的美元,然后是它的一半.

$payprice = round($Price * 2, 0)/2;
Run Code Online (Sandbox Code Playgroud)


Sco*_*ain 13

乘以2,在上面的数字中舍入为0,想要舍入到.5(在您的情况下舍入到小数位数),除以2.

这将使你四舍五入到最接近的.5,加上0并且你有四舍五入到最接近的.50.

如果你想要最近的.25做同样的但是乘以除以4.


Fry*_*Fry 5

function roundnum($num, $nearest){ 
  return round($num / $nearest) * $nearest; 
} 
Run Code Online (Sandbox Code Playgroud)

例如:

$num = 50.55;
$nearest = .50;
echo roundnum($num, $nearest);
Run Code Online (Sandbox Code Playgroud)

返回

50.50
Run Code Online (Sandbox Code Playgroud)

这可以用来四舍五入到任何东西,5cents,25cents,等等......

归功于 ninjured :http ://forums.devshed.com/php-development-5/round-to-the-nearest-5-cents-537959.html