note 34823 modified in function.round by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 16:25:22 +0000 |
| Subject: | note 34823 modified in function.round by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154823@lists.php.net to get a copy of this message | ||
The round() function may indeed work properly with half-values (eg. 1.5), but this little method
will give you peace of mind. Add some "fuzz" to your function with a miniscule delta
value.
<?php
$delta = 0.00001;
$x = round($x+$delta);
?>
This is fine, unless $x has a value of 1.49999 ... if you worried about that, use this method
instead:
<?php
if(($x-floor($x))==0.5){
$x+=$delta;
}
$x = round($x);
?>
you can change your "optimistic" delta into a "pessimistic" delta by subtracting
instead of adding.
Cheers,
Ian Ring
--was--
The round() function may indeed work properly with half-values (eg. 1.5), but this little method
will give you peace of mind. Add some "fuzz" to your function with a miniscule delta
value.
$delta = 0.00001;
$x = round($x+$delta);
This is fine, unless $x has a value of 1.49999 ... if you worried about that, use this method
instead:
if(($x-floor($x))==0.5){
$x+=$delta;
}
$x = round($x);
you can change your "optimistic" delta into a "pessimistic" delta by subtracting
instead of adding.
Cheers,
Ian Ring
http://php.net/manual/en/function.round.php