Rounding to the Nearest Ending Digits

瘦欲@ 提交于 2019-12-06 03:32:45
nickf

This works for me:

function roundToDigits($num, $suffix, $type = 'round') {
    $pow = pow(10, floor(log($suffix, 10) + 1));
    return $type(($num - $suffix) / $pow) * $pow + $suffix; 
};

$type should be either "ceil", "floor", or "round"

I think this should work, and it's more elegant to me, at least:

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;
}

Edit: Added what I think you want from negative inputs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!