note 78814 added to function.round

From: Date: Mon, 29 Oct 2007 13:23:57 +0000
Subject: note 78814 added to function.round
Groups: php.notes 
Request: Send a blank email to php-notes+get-131810@lists.php.net to get a copy of this message
[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 ;)? ---- Server IP: 87.238.162.147 Probable Submitter: 84.192.163.141 ---- Manual Page -- http://www.php.net/manual/en/function.round.php Edit -- https://master.php.net/note/edit/78814 Del: integrated -- https://master.php.net/note/delete/78814/integrated Del: useless -- https://master.php.net/note/delete/78814/useless Del: bad code -- https://master.php.net/note/delete/78814/bad+code Del: spam -- https://master.php.net/note/delete/78814/spam Del: non-english -- https://master.php.net/note/delete/78814/non-english Del: in docs -- https://master.php.net/note/delete/78814/in+docs Del: other reasons-- https://master.php.net/note/delete/78814 Reject -- https://master.php.net/note/reject/78814 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131810) next »