Skip to content

Instantly share code, notes, and snippets.

@AminulBD
Last active August 2, 2021 13:22
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 AminulBD/911c1d6d15a61c3cb78f514d4776090d to your computer and use it in GitHub Desktop.
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.
<?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