我有一个函数,可以将数字四舍五入到以$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
提前感谢您!
附注:此问题与舍入到最接近的倍数无关。