note 83518 added to function.ceil
| From: | benjamwelker*gmail at osu1 dot php dot net | Date: | Thu, 29 May 2008 16:57:11 +0000 |
| Subject: | note 83518 added to function.ceil | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-139985@lists.php.net to get a copy of this message | ||
@ zariok
that function is nice, but it only works for positive numbers, causing negative numbers to be
grossly incorrect.
e.g.-
round_up(4.765, 2) => 4.77 as expected
round_up(-4.765, 2) => -3.23
a couple modified versions of your function (depending on which one you really want):
// rounds towards positive infinity
function round_up($value, $precision = 0) {
$sign = (0 <= $value) ? +1 : -1;
$amt = explode('.', $value);
$precision = (int) $precision;
if (strlen($amt[1]) > $precision) {
$next = (int) substr($amt[1], $precision);
$amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);
if (0 != $next) {
if (+1 == $sign) {
$amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision -
1).'1') * $sign);
}
}
}
else {
$amt[1] = (float) (('.'.$amt[1]) * $sign);
}
return $amt[0] + $amt[1];
}
// rounds away from zero
function round_out($value, $precision = 0) {
$sign = (0 <= $value) ? +1 : -1;
$amt = explode('.', $value);
$precision = (int) $precision;
if (strlen($amt[1]) > $precision) {
$next = (int) substr($amt[1], $precision);
$amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);
if (0 != $next) {
$amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision -
1).'1') * $sign);
}
}
else {
$amt[1] = (float) (('.'.$amt[1]) * $sign);
}
return $amt[0] + $amt[1];
}
----
Server IP: 209.41.74.194
Probable Submitter: 166.70.178.114
----
Manual Page -- http://www.php.net/manual/en/function.ceil.php
Edit -- https://master.php.net/note/edit/83518
Del: integrated -- https://master.php.net/note/delete/83518/integrated
Del: useless -- https://master.php.net/note/delete/83518/useless
Del: bad code -- https://master.php.net/note/delete/83518/bad+code
Del: spam -- https://master.php.net/note/delete/83518/spam
Del: non-english -- https://master.php.net/note/delete/83518/non-english
Del: in docs -- https://master.php.net/note/delete/83518/in+docs
Del: other reasons-- https://master.php.net/note/delete/83518
Reject -- https://master.php.net/note/reject/83518
Search -- https://master.php.net/manage/user-notes.php