Something like this:
echo somefn(2800000000); // outputs '2,8B' for 2,8 billion
echo somefn(2000000); // outputs '2M' for 2 million
echo somefn(5400); // outputs '5,4K' for 5,400
echo somefn('blabla') // outputs 'blabla' as it is because it isn't a number
echo somefn(5) // outputs 5, nothing to simplify
I know it must be really easy code but I wonder if anyone else has something that accounts for maybe other cases that don't pop in my head right now.
/Edit I'm looking for something more in the lines of a generalized, built-in PHP function (or something close to that). Pretty much the same way strtotime()
can handle things like "weeks" or "months".
I don't know of any off the shelf function you can call. Here's one possible solution:
function number_abbr($number) {
if (!is_numeric($number) || $number < 1000)
return $number;
$postfix = array("K", "M", "B", "T");
while ($number >= 1000 && count($postfix) > 0) {
$number /= 1000;
$append = array_shift($postfix);
}
// if the number is still greater than 1000...
if ($number > 1000)
return "a lot";
// return the output
return sprintf("%1.1f" . $append, $number);
}
This seemed to work pretty nicely:
function somefn( $num) {
if( !is_numeric( $num)) return $num;
$num = floatval( $num);
$suffix = '';
if( $num / 1000000000 > 1) {
$num = $num / 1000000000;
$suffix = 'B';
}
elseif( $num / 1000000 > 1) {
$num = $num / 1000000;
$suffix = 'M';
}
elseif( $num / 1000 > 1) {
$num = $num / 1000;
$suffix = 'K';
}
return number_format( $num, 1, ',', ',') . ' ' . $suffix;
}
This outputs:
2,8 B
2,0 M
5,4 K
blabla
5,0
You can of course tweak it to precisely match the desired output. Here is a demo showing it in action.
Loop-free.
function abbr_number($size,$decimals=2,$sizes = array("","K","M","B","T")) {
if(!is_numeric($size) || $size==0) return ($size);
if(!is_numeric($decimals) || $decimals<0) $decimals=2;
$size=abs($size);
$n = ($size/pow(1000,($i = floor(log($size, 1000)))))*
(isset($sizes[$i])?1:pow(1000,$i-(count($sizes)-1)).end($sizes));
return ($size<=0?'-':'').($size>0 ? round($n*pow(10,$decimals))/pow(10,$decimals):$n).
(isset($sizes[$i])?$sizes[$i]:array_pop($sizes));
}
echo(implode('<br />',array(
abbr_number(2800000000),
abbr_number(2000000),
abbr_number(5400),
abbr_number('blabla'),
abbr_number(5),
abbr_number(pow(rand(),rand(1,5)))
)));