Tag Archives: php methods

Rounding up and rounding out numbers with PHP functions

php-banner

Some PHP functions to round numbers up and out, with examples.

// Round "up" method
// Rounds up to the specified number of decimal places
function roundUp ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ceil($value * $mult) / $mult;
}

// Round "out" method
// rounds a float away from zero to a specified number of decimal places
function roundOut ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ($value >= 0 ? ceil($value * $mult):floor($value * $mult)) / $mult;
}

echo roundUp (56.77001, 2); // displays 56.78
echo roundUp (-0.453001, 4); // displays -0.453
echo roundOut (56.77001, 2); // displays 56.78
echo roundOut (-0.453001, 4); // displays -0.4531

 

Share this post:
read more