title: Rounding to the Nearest Ending Digits
body: <p>I have the following function that <strong>rounds a number to the nearest number ending with the digits of $nearest</strong>, and I was wondering if there is <strong>a more elegant way</strong> of doing the same.</p>
  
  <pre><code>/**
   * 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 &lt;= $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) &lt;= abs($floor)) ? $ceil : $floor;
              break;
          }
      }
  
      if ($number &lt; 0)
      {
          $result *= -1;
      }
  
      return $result;
  }
  </code></pre>
  
  <p>Some examples:</p>
  
  <pre><code>roundNearest(86, 9); // 89
  roundNearest(97, 9); // 99
  roundNearest(97, 9, 'floor'); // 89
  </code></pre>
  
  <p>Thanks in advance!</p>
  
  <p><strong>PS: This question is <em>not</em> about rounding to the <em>nearest multiple</em>.</strong></p>