While looking at PHP.net this afternoon, I saw a comment in round()
for two functions for rounding UP
and DOWN
(as opposed to just HALF_UP
and DOWN
). I liked the suggestion, but wanted a solution that was one function instead of 3, so I came up with the following:
define('PHP_ROUND_UP', 11);
define('PHP_ROUND_DOWN', 12);
function fround($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
if(is_string($number)) {
$number = preg_replace('/,/','',$number);
}
if (is_numeric($number) && !empty($number)) {
switch($mode) {
case PHP_ROUND_UP:
case PHP_ROUND_DOWN:
$invert = (bool) ($number < 0);
if($invert) {
$number *= -1;
}
if (!empty($precision)) {
$precision = pow(10, (int) $precision);
$number *= $precision;
}
if ($mode == PHP_ROUND_UP) {
$number = ceil($number);
} else {
$number = floor($number);
}
if (!empty($precision) && !empty($number)) {
$number /= $precision;
}
if($invert) {
$number *= -1;
}
break;
default:
$number = round($number, $precision, $mode);
break;
}
}
return (float) $number;
}
My questions are about overhead/performance, and really anything else you may have to say. For options other than PHP_ROUND_UP
or PHP_ROUND_DOWN
it adds minimal overhead, save for stripping commas if the input number is a string (I realize this is additional to what PHP's round()
does), so I guess I am asking about the internal logic for PHP_ROUND_UP
and PHP_ROUND_DOWN
.
The comment that sparked this for me is here.