Skip to content

Instantly share code, notes, and snippets.

@BorisAnthony
Last active January 1, 2016 14:03
Show Gist options
  • Save BorisAnthony/61a04b3d5664aceed3bf to your computer and use it in GitHub Desktop.
Save BorisAnthony/61a04b3d5664aceed3bf to your computer and use it in GitHub Desktop.
PHP Round Full Up and Full Down
<?php
/*
----------------------------------------------------------
FULL ROUND UP and DOWN
Boris Anthony .net - 2016-01-01
Fully agreed with this statement:
"In my opinion PHP's ROUND() function lacks two flags:
- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.
It's often necessary to always round up, or down to varying positions."
Inspired and based on comments from PHP Documentation:
http://php.net/manual/en/function.round.php
Particularily:
http://php.net/manual/en/function.round.php#114573
and
http://php.net/manual/en/function.round.php#115605
----------------------------------------------------------
*/
function round_up($value, $places)
{
$mult = pow(10, abs($places));
return $places < 0 ?
ceil($value / $mult) * $mult :
ceil($value * $mult) / $mult;
}
function round_down($value, $places)
{
$mult = pow(10, abs($places));
return $places < 0 ?
floor($value / $mult) * $mult :
floor($value * $mult) / $mult;
}
// Pretty Print examples --------------------------
echo "<pre>";
// Round Up examples
echo round_up(12345.234, 2)."\n"; // 12345.24
echo round_up(12345.234, 1)."\n"; // 12345.3
echo round_up(12345.234, 0)."\n"; // 12346
echo round_up(12345.234, -1)."\n"; // 12350
echo round_up(12345.234, -2)."\n"; // 12400
echo round_up(12345.234, -3)."\n"; // 13000
echo round_up(12345.234, -4)."\n\n"; // 20000
// Round Down examples
echo round_down(12345.234, 2)."\n"; // 12345.23
echo round_down(12345.234, 1)."\n"; // 12345.2
echo round_down(12345.234, 0)."\n"; // 12345
echo round_down(12345.234, -1)."\n"; // 12340
echo round_down(12345.234, -2)."\n"; // 12300
echo round_down(12345.234, -3)."\n"; // 12000
echo round_down(12345.234, -4)."\n"; // 10000
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment