note 84308 deleted from function.round by danbrown

From: Date: Sun, 17 May 2009 16:12:08 +0000
Subject: note 84308 deleted from function.round by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154765@lists.php.net to get a copy of this message
Note Submitter: Jeremy (aka Mr. Pet Gerbil) ---- 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); } ?>

« previous php.notes (#154765) next »