Math
|
|
|
|
<?php /*
Function: fmtnum ($data, $decimal, $format)
Author: Matt Hoskins (matth@npgco.com)
Date: 12/11/2002
License: GPL
Description: numfmt() allows you to format large numbers into easily
readable ones. For example:
Input Returns
----- -------
1500000000 1.50 G
1200000 1.20 M
1334 1.33 K
By specifying the format as FMT_SCI, the function will
return the number in scientic notation. You can also
force the conversion into a specific type by specifying
the format.
Usage: int numfmt (int $data, [int $decimal], [string $format])
$data -- The number you want converted
$decimal -- The number of decimal points to return.
(defaults to 2, if not specified)
$format -- Forces the function to return in the specified
format.
FMT_GIGA -- Returns with G postfix
FMT_MEGA -- Returns with M postfix
FMT_KILO -- Returns with K postfix
FMT_SCI -- Returns in Scietific Notation
Any feedback is greatly appreciated.
*/ function fmtnum ($data) {
$format = @func_get_arg(2);
$decimal = @func_get_arg(1);
if (!isset($decimal)) { $decimal = 2; }
switch ($format) {
case "FMT_GIGA":
$data = sprintf("%0.".$decimal."f G", $data / 1000000000);
break;
case "FMT_MEGA":
$data = sprintf("%0.".$decimal."f M", $data / 1000000);
break;
case "FMT_KILO":
$data = sprintf("%0.".$decimal."f K", $data / 1000);
break;
case "FMT_SCI":
if ($data < 1) {
while ($data < 1) {
$data *= 10;
$power++;
}
$data = sprintf("%0.".$decimal."f x 10<sup>-".$power."</sup>", $data);
} elseif ($data > 10) {
while ($data > 10) {
$data /= 10;
$power++;
}
$data = sprintf("%0.".$decimal."f x 10<sup>".$power."</sup>", $data);
}
break;
default:
if ($data > 1000000000 ) {
$data = sprintf("%0.".$decimal."f G", $data / 1000000000);
} elseif ($data > 1000000 ) {
$data = sprintf("%0.".$decimal."f M", $data / 1000000);
} elseif ( $data > 1000 ) {
$data = sprintf("%0.".$decimal."f K", $data / 1000);
}
}
return $data;
} ?>
|
|
|
Usage Example
|
fmtnum(1234567890, 4, "FMT_GIGA")
returns "1.2345 G"
numfmt(.000001, 0, "FMT_SCI")
returns: "1x10-5"
|
|
|
Rate This Script
|
|
|
|