Skip to content

Instantly share code, notes, and snippets.

@mmollick
Forked from bcole808/numberAbbreviation.php
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save mmollick/8857f401e172f5e03e4c to your computer and use it in GitHub Desktop.

Select an option

Save mmollick/8857f401e172f5e03e4c to your computer and use it in GitHub Desktop.
<?php
/**
* Shorten large numbers into abbreviations (i.e. 15,000 = 15K, 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;
$display = number_format( $display_num, $decimals );
if ( $display % 1 === 0 ) {
$display = number_format( $display, 0 );
}
return $display . $abbrev;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment