2.4 Rounding Arbitrary-Precision Numbers


2.4 Rounding Arbitrary-Precision Numbers

You want to round an arbitrary precision number to a certain decimal place (for example, the hundredths place).

Technique

Write your own function, bcround() :

 <?php $rounded = bcround($num,$decimalplaces); ?> 

Or use sprintf() with the formatting options:

 <?php $rounded = sprintf("%.6f", $num); // Rounds to 6 decimal places ?> 

Comments

sprintf() , in my opinion, is by far the easiest method of rounding an arbitrary precision number. You just use %. num f where num is the number of places you want to round to, and sprintf() does the rest for you. However, sprintf() rounds only to normal floating-point precision. You can't use it if you want to round to the fiftieth decimal place.

Note

To perform arbitrary precision arithmetic you can also use the GMP (GNU MP) extension.


What is sprintf() ? sprintf() is a function that takes a variable, processes it, and returns the data of that variable in the desired format. Just like its counterpart printf() , which enables you to print the value of a variable in a desired format, sprintf() offers special formatting codes to help you convert between. For more information, see the PHP manual: http://www.php.net/function.sprintf.php.

The bcround() function rounds an arbitrary precision number to a certain number of decimal places. That means you can round numbers above the domain of a floating-point number:

 <?php $number = 34.697405454021; $rounded = bc_round($number, 5); // $rounded is now 34.69741 ?> 

Here is the source code of the bc_round() function:

 function bc_round($num, $count) {     // Split up the number     list($whole_num, $decimal) = explode(".", strval($num));     // Let's work with the decimal     $decimal_string = substr($decimal, 0, $count);     $determinant = substr($decimal, $count, 1);     // Check for special cases     if (substr($decimal, 0, 1) == "9") {        $len = strlen($decimal_string);        for ($i=0; $i<$len; $i++) {           if (substr($decimal_string, $i, 1) == "9") {              $true++;           }        }        if ($true == $len) {           $whole_num++;           return $whole_num;        }     }     // Round for non-special cases     if ($determinant >= 5)        $decimal_string++;     // Put It Back together     $denom = pow(10, strlen($decimal_string));     $decimal_corrected = $decimal_string / $denom;     return("$whole_num.$decimal_corrected"); } 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net