note 114663 added to function.round
| From: | spectrumcat at gmail dot com | Date: | Wed, 19 Mar 2014 14:22:58 +0000 |
| Subject: | note 114663 added to function.round | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198981@lists.php.net to get a copy of this message | ||
In case someone will need a "graceful" rounding (that changes it's precision to get a
non 0 value) here's a simple function:
function gracefulRound($val, $min = 2, $max = 4) {
$result = round($val, $min);
if ($result == 0 && $min < $max) {
return gracefulRound($val, ++$min, $max);
} else {
return $result;
}
}
Usage:
$_ = array(0.5, 0.023, 0.008, 0.0007, 0.000079, 0.0000048);
foreach ($_ as $val) {
echo "{$val}: ".gracefulRound($val)."\n";
}
Output:
0.5: 0.5
0.023: 0.02
0.008: 0.01
0.0007: 0.001
0.000079: 0.0001
0.0000048: 0
----
Server IP: 91.199.167.223
Probable Submitter: 83.163.205.204
----
Manual Page -- http://php.net/manual/en/function.round.php
Edit -- https://master.php.net/note/edit/114663
Del: integrated -- https://master.php.net/note/delete/114663/integrated
Del: useless -- https://master.php.net/note/delete/114663/useless
Del: bad code -- https://master.php.net/note/delete/114663/bad+code
Del: spam -- https://master.php.net/note/delete/114663/spam
Del: non-english -- https://master.php.net/note/delete/114663/non-english
Del: in docs -- https://master.php.net/note/delete/114663/in+docs
Del: other reasons-- https://master.php.net/note/delete/114663
Reject -- https://master.php.net/note/reject/114663
Search -- https://master.php.net/manage/user-notes.php