note 105870 modified in function.floor by danbrown
| From: | danbrown@php.net | Date: | Wed, 21 Sep 2011 18:35:20 +0000 |
| Subject: | note 105870 modified in function.floor by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183332@lists.php.net to get a copy of this message | ||
The better way to round up/down to the nearest hundred (or thousand, etc.) is with roundBetter():
<?php
// This function is backwards compatible with round(),
// but provides an optional extra argument which,
// if set and not null, allows you to override the default
// rounding direction. See examples below.
function roundBetter($number, $precision = 0, $mode = PHP_ROUND_HALF_UP, $direction = NULL) {
if (!isset($direction) || is_null($direction)) {
return round($number, $precision, $mode);
}
else {
$factor = pow(10, -1 * $precision);
return strtolower(substr($direction, 0, 1)) == 'd'
? floor($number / $factor) * $factor
: ceil($number / $factor) * $factor;
}
}
// roundBetterUp(1999, -3) => 2000
// roundBetterUp(1001, -3) => 2000
function roundBetterUp($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
return roundBetter($number, $precision, $mode, 'up');
}
// roundBetterDown(1999, -3) => 1000
// roundBetterDown(1001, -3) => 1000
function roundBetterDown($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
return roundBetter($number, $precision, $mode, 'down');
}
?>
--was--
The better way to round up/down to the nearest hundred (or thousand, etc.) is with roundBetter():
// This function is backwards compatible with round(),
// but provides an optional extra argument which,
// if set and not null, allows you to override the default
// rounding direction. See examples below.
function roundBetter($number, $precision = 0, $mode = PHP_ROUND_HALF_UP, $direction = NULL) {
if (!isset($direction) || is_null($direction)) {
return round($number, $precision, $mode);
}
else {
$factor = pow(10, -1 * $precision);
return strtolower(substr($direction, 0, 1)) == 'd'
? floor($number / $factor) * $factor
: ceil($number / $factor) * $factor;
}
}
// roundBetterUp(1999, -3) => 2000
// roundBetterUp(1001, -3) => 2000
function roundBetterUp($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
return roundBetter($number, $precision, $mode, 'up');
}
// roundBetterDown(1999, -3) => 1000
// roundBetterDown(1001, -3) => 1000
function roundBetterDown($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
return roundBetter($number, $precision, $mode, 'down');
}
http://php.net/manual/en/function.floor.php