Skip to content

Instantly share code, notes, and snippets.

@EXayer
Forked from bcole808/numberAbbreviation.php
Last active February 10, 2021 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EXayer/18f0b8331aa84d7976d6423de0ca036e to your computer and use it in GitHub Desktop.
Save EXayer/18f0b8331aa84d7976d6423de0ca036e to your computer and use it in GitHub Desktop.
Shorten large numbers into abbreviations (i.e. 1,500 = 1.5k), (slightly optimized)
<?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 = [1000000000000 => 'T', 1000000000 => 'B', 1000000 => 'M', 1000 => 'K', 1 => ''];
foreach ($abbrevs as $diapason_min => $abbrev) {
if ($number >= $diapason_min) {
$display_num = $number / $diapason_min;
$decimals = ($diapason_min >= 1000 && round($display_num) < 100) ? 1 : 0;
return number_format($display_num, $decimals) . $abbrev;
}
}
return $number;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment