note 124758 deleted from function.round by cmb
| From: | cmb@php.net | Date: | Fri, 28 Feb 2020 06:58:56 +0000 |
| Subject: | note 124758 deleted from function.round by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214247@lists.php.net to get a copy of this message | ||
Note Submitter: Astro
----
Sorry, my previous function doesn't work with negative numbers and zero (and this wasn't
my case). If you works with negative numbers and zero you could try this:
NumberPrecision($n, $precision=0, $is_round=true)
{
$r = (($is_round) ? 5 : 1);
$r *= pow(10, -($precision+1));
$n += (($n < 0) ? -$r : $r);
$comma = '.';
$n = number_format($n, $precision+1, $comma, '');
$n .= $comma;
list($n, $frac) = explode($comma, $n, 2);
$n = rtrim(rtrim($n, $comma) . $comma . substr($frac, 0, $precision), $comma);
return ($n);
}
Also this works with numbers like 0.3 and numbers with exponent. Don't forget to test it for
your cases.