note 43092 deleted from function.number-format by tomsommer
| From: | tomsommer@php.net | Date: | Wed, 09 Jun 2004 21:45:35 +0000 |
| Subject: | note 43092 deleted from function.number-format by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-70599@lists.php.net to get a copy of this message | ||
Note Submitter: jim@NOSPAM.conxiondesigns.com
----
This script will allow you to round to a specific decimal place and the number can be negative, less
than zero, or whatever.
Some tests can be found here to show its use:
http://www.conxiondesigns.com/laboratory/php/round_decimals/
<?php
function roundDecimals($n, $dp) {
if($n < 0) {
$isNegative = true;
}
$expanded = (int)(abs($n) * pow(10, $dp+1));
if($expanded % 10 == 0) {
$expanded = ($expanded / pow(10, $dp));
} else if ($expanded % 10 >= 5) {
$expanded = ((int)($expanded/10) + 1);
$expanded = $expanded/pow(10,$dp);
} else if ($expanded % 10 < 5) {
$expanded = (int)($expanded/10);
$expanded = $expanded/pow(10,$dp);
}
$n = $expanded;
if($isNegative == true) {
$n = $n * -1;
}
return $n;
}
?>
In this function $n should be the number to input, $dp should be an integer of how many decimal
places you want after rounding. It returns a float. This however is not enough when you go to
display the number because we need to force php to display trialing zeros. You must present it in
the following way to get results which are accurate:
<?php printf("%.1f",roundDecimals(20.562, 1)); ?>
Where the %.1f and second argument (2 in this case) must correspond. So if you wanted the 5th
decimal place to be the one rounded to you would have:
<?php printf("%.5f",roundDecimals(20.5628964, 5)); ?>
I find it useful but I am sure there are some flaws in it.
-Jim