note 93339 deleted from function.round by danbrown
| From: | danbrown@php.net | Date: | Thu, 10 Dec 2009 03:20:28 +0000 |
| Subject: | note 93339 deleted from function.round by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-163806@lists.php.net to get a copy of this message | ||
Note Submitter: BigueNique at yahoo dot ca
----
For you folks who are still using PHP4, or just want their code to stay backward compatible,
here's a dirty trick to simulate the PHP_ROUND_HALF_UP mode.
By default, round() will round down (PHP_ROUND_HALF_DOWN):
<?php
echo round(0.5); // gives 0
?>
To simulate round up, simply add the biggest rounded power of 10, like this:
<?php
echo round(0.5 + 0.1); // gives 1 instead of 0
echo round(1.45/10 + 0.001, 2); // gives 0.15 instead of 0.14
?>
This could be generalized:
<?php
function round_up($val, $precision) {
return round($val + 10^(-($precision+1)), $precision);
}
?>