Last active
June 28, 2019 04:49
-
-
Save mattkomarnicki/49f70c4c2f60efa31b4a967077ea2ffa to your computer and use it in GitHub Desktop.
Formats given integer into short version with a suffix. For example "1500" will become "1K+".
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 | |
if (!function_exists('format_number_in_k_notation')) { | |
function format_number_in_k_notation(int $number): string | |
{ | |
$suffixByNumber = function () use ($number) { | |
if ($number < 1000) { | |
return sprintf('%d', $number); | |
} | |
if ($number < 1000000) { | |
return sprintf('%d%s', floor($number / 1000), 'K+'); | |
} | |
if ($number >= 1000000 && $number < 1000000000) { | |
return sprintf('%d%s', floor($number / 1000000), 'M+'); | |
} | |
if ($number >= 1000000000 && $number < 1000000000000) { | |
return sprintf('%d%s', floor($number / 1000000000), 'B+'); | |
} | |
return sprintf('%d%s', floor($number / 1000000000000), 'T+'); | |
}; | |
return $suffixByNumber(); | |
} | |
} | |
dump(format_number_in_k_notation(123)); // "123" | |
dump(format_number_in_k_notation(73000)); // "73K+" | |
dump(format_number_in_k_notation(216000)); // "216K+" | |
dump(format_number_in_k_notation(50400123)); // "50M+" | |
dump(format_number_in_k_notation(12213500100600)); // "12T+" | |
die; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment