【问题标题】:Rounding to the Nearest Ending Digits四舍五入到最近的结束数字
【发布时间】:2009-10-12 15:32:58
【问题描述】:

我有以下函数将数字四舍五入到以 $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

提前致谢!

PS:这个问题不是关于四舍五入到最近的倍数

【问题讨论】:

  • 你为什么要重新发明轮子?

标签: php math numbers rounding


【解决方案1】:

这对我有用:

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 用于我的问题中提供的示例。
  • 您是否更改了$type 参数? roundToDigits(94,9,'floor')==89, roundToDigits(94,9,'ceil')==99, roundToDigits(94,9,'round')==99
  • 糟糕,我没有! :O 整洁的解决方案,我只需将$pow = pow(10, floor(log($suffix, 10) + 1)); 更改为也处理小数。谢谢!
  • 刚刚来找我,你会如何处理$suffix = 0
【解决方案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;
}

编辑:添加了我认为你想要的负面输入。

【讨论】:

  • 重复太多,不够优雅。
  • @Reinis I.:好吧,我让它更优雅一点。
猜你喜欢
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
相关资源
最近更新 更多