Last active
August 2, 2021 13:22
-
-
Save AminulBD/911c1d6d15a61c3cb78f514d4776090d to your computer and use it in GitHub Desktop.
Make number abbreviation like Trillion (T), Billion (B), Million (M), Thousand (K) etc.
This file contains hidden or 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 | |
/** | |
* Make long number as abbreviation | |
* | |
* @param float $number | |
* | |
* @return string | |
*/ | |
function makeNumberAbbr(float $number): string | |
{ | |
$abbrevs = [12 => 'T', 9 => 'B', 6 => 'M', 3 => 'K', 0 => '']; | |
foreach ($abbrevs as $exponent => $abbrev) { | |
if (abs($number) >= pow(10, $exponent)) { | |
$display = $number / pow(10, $exponent); | |
$decimals = ($exponent >= 3 && round($display) < 100) ? 1 : 0; | |
$number = number_format($display, $decimals) . $abbrev; | |
break; | |
} | |
} | |
return $number; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment