Skip to content

Instantly share code, notes, and snippets.

@bcole808
Created March 5, 2014 17:18
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save bcole808/9371754 to your computer and use it in GitHub Desktop.
Save bcole808/9371754 to your computer and use it in GitHub Desktop.
Shorten large numbers into abbreviations (i.e. 1,500 = 1.5k)
<?php
/**
* Shorten large numbers into abbreviations (i.e. 1,500 = 1.5k)
*
* @param int $number Number to shorten
* @return String A number with a symbol
*/
function numberAbbreviation($number) {
$abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => "");
foreach($abbrevs as $exponent => $abbrev) {
if($number >= pow(10, $exponent)) {
$display_num = $number / pow(10, $exponent);
$decimals = ($exponent >= 3 && round($display_num) < 100) ? 1 : 0;
return number_format($display_num,$decimals) . $abbrev;
}
}
}
?>
@anteksiler
Copy link

When the $number is 0, this returns empty.

@kmkroski
Copy link

I added 'return $number;' as the last line of the function to solve the 0 issue.

@NinoSkopac
Copy link

seems to work good, thank you sir, you are a gentleman and a scholar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment