四舍五入到最接近的50美分


Rounding to nearest 50 cents

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

    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;

我知道如果我使用round($Price,2);我会有两位小数,但有办法四舍五入到最接近的50美分吗?

一些简单的数学应该可以做到。与其四舍五入到最接近的50美分,不如将$price的两倍四舍五五入到最近的美元,然后减半。

$payprice = round($Price * 2, 0)/2;

乘以2,四舍五入到上面要四舍五进到.5的数字中的0(在您的情况下,四舍四入到小数点后1位),除以2。

这将使你四舍五入到最接近的值。5,加上0,你就得到了最接近的50。

如果你想要最接近的.25,也可以这样做,但要乘以4。

function roundnum($num, $nearest){ 
  return round($num / $nearest) * $nearest; 
} 

例如:

$num = 50.55;
$nearest = .50;
echo roundnum($num, $nearest);

返回

50.50

这可以用来四舍五入到任何东西,5美分,25美分,等等…

信用证:http://forums.devshed.com/php-development-5/round-to-the-nearest-5-cents-537959.html

将数字除以最近值,计算ceil,然后乘以最近值以减少有效位数。

function rndnum($num, $nearest){
    return ceil($num / $nearest) * $nearest;
}

Ex。

echo-rndnum(95.5,10)返回100

echo-rndnum(94.5,1)返回95

请注意,如果使用floor而不是round,则由于浮点数的内部精度,需要额外的round。

function roundnum($num, $nearest){ 
  return floor(round($num / $nearest)) * $nearest; 
} 
$num = 16.65;
$nearest = .05;
echo roundnum($num, $nearest);

否则,它将返回16.60而不是16.65

手动

来自手册:echo round(1.95583, 2); // 1.96

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
val
The value to round
precision
The optional number of decimal digits to round to.
mode
One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.

只需更改为:echo round(1.54*2, 0)/2; // 1.5