note 83518 modified in function.ceil by felipe
| From: | felipe@php.net | Date: | Fri, 30 May 2008 11:29:54 +0000 |
| Subject: | note 83518 modified in function.ceil by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-139997@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):
<?php
// 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];
}
?>
--was--
@ 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];
}
http://php.net/manual/en/function.ceil.php