四舍五入到最接近的尾数 [英] Rounding to the Nearest Ending Digits
本文介绍了四舍五入到最接近的尾数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下功能,将数字四舍五入到以$ nearest数字结尾的最接近的数字,我想知道是否有一种更优雅的方式做同样的事情.
I have the following function that rounds a number to the nearest number ending with the digits of $nearest, and I was wondering if there is a more elegant way of doing the same.
/**
* 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:这个问题不是舍入到最近倍数的.
推荐答案
这对我有用:
function roundToDigits($num, $suffix, $type = 'round') {
$pow = pow(10, floor(log($suffix, 10) + 1));
return $type(($num - $suffix) / $pow) * $pow + $suffix;
};
$type
应该是天花板",地板"或圆形"
$type
should be either "ceil", "floor", or "round"
这篇关于四舍五入到最接近的尾数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文