note 70152 deleted from function.round by danbrown

From: Date: Sun, 17 May 2009 16:20:22 +0000
Subject: note 70152 deleted from function.round by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154799@lists.php.net to get a copy of this message
Note Submitter: Hitlers Pet Gerbil ---- In response to boonedocks at gmail dot com Your calculations are slightly incorrect. You only use the formula when the 1/1000 position is equal to 5, otherwise you follow standard rounding proceedures. I wrote a quick snippet which works with the input as a string, uses inline substrings and substitutions. Works VERY fast. <?php function bankers_round ($moneyfloat = null) { $money_str = sprintf("%01.3f", round($moneyfloat, 3)); // convert to rounded (to the nearest thousandth) string $thous_pos = strlen($money_str)-1; // Thousandth string position $hundt_pos = strlen($money_str)-2; // Hundredth string position if ($money_str[$thous_pos] === "5") $money_str[$thous_pos] = ((int)$money_str[$hundt_pos] & 1) ? "9" : "0"; // use a bitwise test, its faster than modulus // The above statement assists round() by setting the thousandth position to 9 or zero if the hundredth is even or odd (respectively) return round($money_str, 2); // Return rounded value } ?> Hitlers Pet Gerbil

« previous php.notes (#154799) next »