我有以下功能将数字四舍五入到最接近的数字,以$ 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:这个问题不关于舍入到最近的多个。
答案 0 :(得分: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”
答案 1 :(得分: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;
}
修改:从负面输入中添加了我想要的想法。