Last active
June 14, 2016 04:29
-
-
Save jam2-hey/54397a009f17e633c07e345980fd1420 to your computer and use it in GitHub Desktop.
Convert your numbers into strings like '10.3K' or '1M' for better readibility.
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 | |
function shortNumber($number, $decimal = 2) | |
{ | |
$suffixes = [ 4 => '', 7 => 'K', 10 => 'M', 13 => 'B', 16 => 'T']; | |
$absNumber = abs($number); | |
$sign = ($number < 0) ? '-' : ''; | |
$magnitude = strlen(floor($absNumber)); // This is dirty, but it gets job done. | |
$exponent = $magnitude % 3 === 0 ? $magnitude - 3 : $magnitude - ($magnitude % 3); | |
if ($magnitude > 16) { | |
$magnitude = 15; | |
$exponent = 12; | |
} | |
$shortNumber = floor(pow(10, $decimal) * ($absNumber / pow(10, $exponent))) / pow(10, $decimal); | |
foreach ($suffixes as $maxMagnitude => $suffix) { | |
if ($magnitude < $maxMagnitude) { | |
$shortNumber .= $suffix; | |
break; | |
} | |
} | |
return $sign . $shortNumber; | |
} |
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 | |
$testCases = [ | |
[ 0, 2, '0' ], | |
[ 999, 2, '999' ], | |
[ 1000, 2, '1K' ], | |
[ 1024, 2, '1.02K' ], | |
[ 99999, 2, '99.99K' ], | |
[ 999999, 2, '999.99K' ], | |
[ 1000000, 2, '1M' ], | |
[ 1234567, 2, '1.23M' ], | |
[ 99999999, 2, '99.99M' ], | |
[ 999999999, 2, '999.99M' ], | |
[ 1000000000, 2, '1B' ], | |
[ 1234567890, 2, '1.23B' ], | |
[ 99999999999, 2, '99.99B' ], | |
[ 999999999999, 2, '999.99B' ], | |
[ 1000000000000, 2, '1T' ], | |
[ 1344843000000, 2, '1.34T' ], | |
[ 9223372036854775807, 2, '9223372.03T' ], | |
]; | |
echo '<pre>'; | |
for ($i = 0; $i < count($testCases); $i++ ) { | |
$arg1 = $testCases[$i][0]; | |
$arg2 = $testCases[$i][1]; | |
$expected = $testCases[$i][2]; | |
$result = shortNumber($arg1, $arg2); | |
echo "($arg1,$arg2) => $result Expected: $expected" . PHP_EOL; | |
} | |
echo '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment