roundDown for php

It seems crazy that php doesn't have a native roundDown function.

It does have round(), which has various modes, but they only provide for rounding down if the starting value is < .5   In some cases, one must round up (the number of boxes needed to hold a quantity of items), but in some, it is necessary to always round down, in particular anywhere that a fraction of something makes no sense because the item is either whole or not.

There are numeric ways to accomplish this, such as:

$rounded_value = floor($value / 10^x) * 10^x

where x is the number of decimal places desired, but the reports I read show each numeric approach seems to have cases where it just fails, where one ends up with what would be a rounded-up value.

So, what to do? String 'math' (many non-php people feeling ill at this point, I'm sure).

function round_down($value, $decimal_places) {
  if ($decimal_places < 0) return ($value, 0);
  $pos = strpos($value, '.');
  if ($pos === FALSE) return $pos;
  return $decimal_places ? substr($value, 0, $pos + $decimal_places + 1) : substr($value, 0, $pos);
}

Note that we test for === FALSE and not boolean (such as !$pos), because strpos() can also return 0 (boolean false) as a valid value.

The results are as follows:
round_down(123.178, 2) = 123.17
round_down(123.178, 1) = 123.1
round_down(123.178, 0) = 123
round_down(123.178, -1) = 123
 

Tags

Add new comment

Markdown

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Missing filter. All text is removed
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.