在 PHP 中四舍五入到最接近的 5 或 9

Round to nearest 5 or 9 in PHP

我需要使用 PHP 函数将产品定价四舍五入到 最近的 5 或 9

例如,它必须总是四舍五入:

3 would round up to 5

7 would round up to 9

目前正在使用以下代码,但这只四舍五入到最接近的 5:

function round_five($num) {
    return round($num*2,-1)/2;
}

如有任何建议,我们将不胜感激 <3

通过检查10除余数是否小于5,取整为5,大于5则取9,否则取余5,return 数字本身。

function my_round($number) {
    $inumber = ceil($number);

    $mod_10 = $inumber % 10;
    $mod_5 = $inumber % 5;

    if ($mod_10 < 5) {
        return $inumber + 5 - $mod_5;
    }

    if ($mod_10 > 5) {
        return $inumber + 10 - $mod_10 - 1;
    }

    return $inumber;
}

echo my_round(243) . PHP_EOL;
echo my_round(247) . PHP_EOL;
echo my_round(5) . PHP_EOL;
echo my_round(9) . PHP_EOL;
echo my_round(10) . PHP_EOL;
echo my_round(0) . PHP_EOL;
echo my_round(5.1) . PHP_EOL;
echo my_round(8.9) . PHP_EOL;
echo my_round(9.1) . PHP_EOL;

输出:

245
249
5
9
15
5
9
9
15

要求有点模糊,因此仍可能对其进行调整以处理各种其他极端情况。

你应该阅读的相关问题:

  • Round up to nearest multiple of five in PHP

这是解决方案:

因为你的问题不是使用核心数学(5 和 9 是任意的)或大指数(最大计数是 5 位数字,0,1,2,3,4),简单地计算数字:

<?php
function rounder($n) {
    $x=[5,9];
    $zz = ceil($n);
     $b = substr((string)$zz, -1); 
    while( !in_array($b,$x) ){
       
        $zz++;     
        $b = substr((string)$zz, -1);
    }
    
    return $zz;
}

$array[] = 243;
$array[] = 247;
$array[] = 249;
$array[] = 240;
$array[] = 250;

foreach($array as $row){

     print rounder($row)."<Br>";

}
unset($row);

========================

输出:

245
249
249
245
255

这可能可以缩短为几行代码......但无论如何

这有点不数学,但应该可行:

function round9($n) {
    $n = ceil($n);
    $r = substr($n,-1) > 5 ? 9 : 5;
    $n = substr($n,0,-1) . $r;
    return $n;
}
  • 第一舍入到最接近的整数
  • 获取最后一位数字
  • 如果大于 5,则用 9 替换最后一位。否则用 5 替换。

更新: 我认为这是一个有趣的问题,现在我们已经从非常不同的角度得到了三个正确的答案,我想我会做一些性能分析出于我自己的好奇心。 neuro_sys 的回答到目前为止获胜!以下是完成 1000 万次迭代的秒级结果:

time to build array: 1.7170281410217
round9: 10.753921985626
my_round: 1.6339750289917
rounder: 16.578145980835

测试是 运行 在 8GB、4 核 Linode VPS 运行ning Ubuntu 16.04 / PHP 7.0.14