繁体   English   中英

四舍五入到最近的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;

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

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

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

乘以2,在上面的数字中舍入为0,想要舍入到.5(在您的情况下舍入到小数位数),除以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

这可用于圆形到任何东西,5cents,25cents等...

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

请注意,如果使用floor而不是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 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 echo round(1.54*2, 0)/2; // 1.5

将数字除以最近,做ceil,然后乘以最近减去有效数字。

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

防爆。

echo rndnum(95.5,10)返回100

echo rndnum(94.5,1)返回95

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM