note 110794 added to function.round
| From: | mdeichelbor at gmail dot com | Date: | Sun, 09 Dec 2012 07:11:59 +0000 |
| Subject: | note 110794 added to function.round | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-192401@lists.php.net to get a copy of this message | ||
I needed to round up half pennies (PHP 5.2.16) and to my dismay, all of the suggested solutions I
tried would round a number like 10.9045 to 10.91 because the rightmost digit, the 5, is rounded up
causing the 4 to become a 5 which is in turn, also rounded up. So here's my solution:
function roundUpFix ($value, $places) {
$newvalue = (($value * pow(10, $places+1)) + 5) / pow(10, $places+1);
return substr($newvalue, 0, strpos($newvalue, '.') + $places+1);
}
echo roundUpFix (10.9045, 2); // prints 10.90
echo roundUpFix (10.9050, 2); // prints 10.91
----
Server IP: 69.147.83.199
Probable Submitter: 72.52.91.2 (proxied: 76.117.6.243)
----
Manual Page -- http://php.net/manual/en/function.round.php
Edit -- https://master.php.net/note/edit/110794
Del: integrated -- https://master.php.net/note/delete/110794/integrated
Del: useless -- https://master.php.net/note/delete/110794/useless
Del: bad code -- https://master.php.net/note/delete/110794/bad+code
Del: spam -- https://master.php.net/note/delete/110794/spam
Del: non-english -- https://master.php.net/note/delete/110794/non-english
Del: in docs -- https://master.php.net/note/delete/110794/in+docs
Del: other reasons-- https://master.php.net/note/delete/110794
Reject -- https://master.php.net/note/reject/110794
Search -- https://master.php.net/manage/user-notes.php