Last active
July 7, 2018 10:50
-
-
Save axieum/fe28891cf2bc7f501fac551caf0683f5 to your computer and use it in GitHub Desktop.
Abbreviate a number (e.g. 1723 => "1.7k")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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