note 110794 rejected from function.round by googleguy

From: Date: Sun, 09 Dec 2012 08:12:44 +0000
Subject: note 110794 rejected from function.round by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192403@lists.php.net to get a copy of this message
Note Submitter: mdeichelbor at gmail dot com ---- 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

« previous php.notes (#192403) next »