note 43092 added to function.number-format
| From: | jim at NOSPAM dot conxiondesigns dot com | Date: | Wed, 09 Jun 2004 15:15:33 +0000 |
| Subject: | note 43092 added to function.number-format | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-70513@lists.php.net to get a copy of this message | ||
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
----
Manual Page -- http://www.php.net/manual/en/function.number-format.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43092
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43092&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43092&report=yes
Search -- http://master.php.net/manage/user-notes.php