Skip to content

Instantly share code, notes, and snippets.

@axieum
Last active July 7, 2018 10:50
Show Gist options
  • Save axieum/fe28891cf2bc7f501fac551caf0683f5 to your computer and use it in GitHub Desktop.
Save axieum/fe28891cf2bc7f501fac551caf0683f5 to your computer and use it in GitHub Desktop.
Abbreviate a number (e.g. 1723 => "1.7k")
<?php
/**
* Abbreviate a number.
*
* @param int $number
* @return string
*/
public static function abbrev(int $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;
}
}
return number_format(is_numeric($display_num) ? $display_num : 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment