note 78814 deleted from function.round by danbrown

From: Date: Sun, 17 May 2009 16:17:00 +0000
Subject: note 78814 deleted from function.round by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154784@lists.php.net to get a copy of this message
Note Submitter: KingIsulgard ---- [quote]I'm sure its been done before, but here's my example of a round up function. This function allows you to specify the number of decimal places to round up to. Eg, when rounding up to 3 decimal places, this function adds 0.0005 to the original value and performs round(), or for 6 decimal places, adds 0.0000005 and performs round(), etc... Hopefully some of you will find it useful: <?php function roundup ($value, $dp) { // Offset to add to $value to cause round() to round up to nearest significant digit for '$dp' decimal places $offset = pow (10, -($dp + 1)) * 5; return round ($value + $offset, $dp); } ?> Please post if you have any comments or improvements on this :-) [/quote] This can be much more efficient: <?php function roundup ($value, $dp) { return ceil($value*pow(10, $dp))/pow(10, $dp); } function rounddown ($value, $dp) { return floor($value*pow(10, $dp))/pow(10, $dp); } ?> Much cleaner, isn't it ;)?

« previous php.notes (#154784) next »