将数字舍入到最接近的整数位

3

我有一个函数,可以将数字四舍五入到以$nearest结尾的最近数字,并且我想知道是否有更加优雅的方法来实现同样的功能。

/**
 * Rounds the number to the nearest digit(s).
 *
 * @param int $number
 * @param int $nearest
 * @return int
 */

function roundNearest($number, $nearest, $type = null)
{
    $result = abs(intval($number));
    $nearest = abs(intval($nearest));

    if ($result <= $nearest)
    {
        $result = $nearest;
    }

    else
    {
        $ceil = $nearest - substr($result, strlen($result) - strlen($nearest));
        $floor = $nearest - substr($result, strlen($result) - strlen($nearest)) - pow(10, strlen($nearest));

        switch ($type)
        {
            case 'ceil':
                $result += $ceil;
            break;

            case 'floor':
                $result += $floor;
            break;

            default:
                $result += (abs($ceil) <= abs($floor)) ? $ceil : $floor;
            break;
        }
    }

    if ($number < 0)
    {
        $result *= -1;
    }

    return $result;
}

一些例子:

roundNearest(86, 9); // 89
roundNearest(97, 9); // 99
roundNearest(97, 9, 'floor'); // 89

提前感谢您!

附注:此问题与舍入到最接近的倍数无关。


你为什么要重复造轮子呢? - markus
2个回答

6
这对我有效:
function roundToDigits($num, $suffix, $type = 'round') {
    $pow = pow(10, floor(log($suffix, 10) + 1));
    return $type(($num - $suffix) / $pow) * $pow + $suffix; 
};

$type应该是"ceil"、"floor"或"round"中的一个。


始终向下舍入数字,在我的问题中提供的示例中返回 798989 - Alix Axel
你改变了 $type 参数吗? roundToDigits(94,9,'floor')==89roundToDigits(94,9,'ceil')==99roundToDigits(94,9,'round')==99 - nickf
哎呀,我没有这样做!:O 很棒的解决方案,我只需要将 $pow = pow(10, floor(log($suffix, 10) + 1)); 更改一下,以处理小数。谢谢! - Alix Axel
刚刚想到,你会如何处理 $suffix = 0 - Alix Axel

2

我认为这样做应该可以,并且对我来说更加优雅,至少是这样:

function roundNearest($number, $nearest, $type = null)
{
  if($number < 0)
    return -roundNearest(-$number, $nearest, $type);

  $nearest = abs($nearest);
  if($number < $nearest)
    return $nearest;

  $len = strlen($nearest);
  $pow = pow(10, $len);
  $diff = $pow - $nearest;

  if($type == 'ciel')
    $adj = 0.5;
  else if($type == 'floor')
    $adj = -0.5;
  else
    $adj = 0;

  return round(($number + $diff)/$pow + $adj)*$pow - $diff;
}

编辑: 添加了我认为您想要的负输入内容。


重复太多了,不够优雅。 - slikts
@Reinis I.:好的,我把它变得更加优雅了一点。 - Kip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接