note 84308 added to function.round
| From: | (akaMr.PetGerbil) | Date: | Tue, 08 Jul 2008 21:09:34 +0000 |
| Subject: | note 84308 added to function.round | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-141278@lists.php.net to get a copy of this message | ||
My function I wrote back in ... 2006 ... has a bug or two in it. First off, I didn't have a
precision factor, something I found to require later on. Second, it didn't return proper values
for rounding when there are digits following the digit after the precision digit (now that's a
long winded sentence). I've tested it with as many possible variables as I can think of. Time
to give it to you guys to really destroy.
Jeremy
<?php
function bankers_round ($x, $precision = 2) {
$p = $precision + 1; $x_str = (string)$x; # Set precision identifier and
convert input to a string (for substrings)
$x_t_pos = strpos($x_str, '.') + $p; $x_h_pos = $x_t_pos - 1; # Get positions of
digits we're interested in
/* Now this is the real math
* If the digit after the precision digit is a 5:
* if the precision digit is even, round up
* if the precision digit is odd, and there are no digits following the digit after the
precision digit, round down
* if the precision digit is odd, and there are digits following the digit after the
precision digit, round up
*/
if ($x_str[$x_t_pos] == 5) $x_str[$x_t_pos] = ((int)$x_str[$x_h_pos] & 1) ? 9 :
($x-round($x_str, $p) > 0) ? 9 : 0;
return (float) round ($x_str, $precision);
}
?>
----
Server IP: 66.207.199.35
Probable Submitter: 72.138.230.145
----
Manual Page -- http://www.php.net/manual/en/function.round.php
Edit -- https://master.php.net/note/edit/84308
Del: integrated -- https://master.php.net/note/delete/84308/integrated
Del: useless -- https://master.php.net/note/delete/84308/useless
Del: bad code -- https://master.php.net/note/delete/84308/bad+code
Del: spam -- https://master.php.net/note/delete/84308/spam
Del: non-english -- https://master.php.net/note/delete/84308/non-english
Del: in docs -- https://master.php.net/note/delete/84308/in+docs
Del: other reasons-- https://master.php.net/note/delete/84308
Reject -- https://master.php.net/note/reject/84308
Search -- https://master.php.net/manage/user-notes.php