note 109352 deleted from function.round by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:40:23 +0000 |
| Subject: | note 109352 deleted from function.round by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189202@lists.php.net to get a copy of this message | ||
Note Submitter: agroveland at gmail dot com
----
Re: chop a number to x decimal places without rounding up. You can subtract a cheat value (.5 * the
smallest decimal place you want) then round as normal. So if you want 3 decimal places, you
subtract 0.0005. Rounds to negative decimal place also.
<?php
function chopRound($n, $p){
return round($n-(5/(pow(10,$p+1))), $p);
}
echo chopRound(0.164999, 3); // 0.164
echo chopRound(3599.123, -2); // 3500
?>
In the first example, if you add enough 9's onto the number, it will eventually return 0.165.
Still, it's pretty quick.