note 70152 added to function.round

From: Date: Wed, 04 Oct 2006 20:47:09 +0000
Subject: note 70152 added to function.round
Groups: php.notes 
Request: Send a blank email to php-notes+get-118065@lists.php.net to get a copy of this message
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 ---- Server IP: 216.235.15.211 Probable Submitter: 24.207.33.160 ---- Manual Page -- http://www.php.net/manual/en/function.round.php Edit -- https://master.php.net/note/edit/70152 Del: integrated -- https://master.php.net/note/delete/70152/integrated Del: useless -- https://master.php.net/note/delete/70152/useless Del: bad code -- https://master.php.net/note/delete/70152/bad+code Del: spam -- https://master.php.net/note/delete/70152/spam Del: non-english -- https://master.php.net/note/delete/70152/non-english Del: in docs -- https://master.php.net/note/delete/70152/in+docs Del: other reasons-- https://master.php.net/note/delete/70152 Reject -- https://master.php.net/note/reject/70152 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118065) next »