fork download
  1. <?php
  2.  
  3. function num_short($n, $precision = 1) {
  4. if ($n < 1000) {
  5. $n_format = round($n);
  6. } else if ($n < 1000000) {
  7. $n_format = round($n / 1000, $precision) . 'K';
  8. } else if ($n < 1000000000) {
  9. $n_format = round($n / 1000000, $precision) . 'M';
  10. } else {
  11. $n_format = round($n / 1000000000, $precision) . 'B';
  12. }
  13. return $n_format;
  14. }
  15.  
  16. echo num_short(5000, 1)."\n"; //outputs 5K
  17. echo num_short(5004, 1)."\n"; //outputs 5K
  18. echo num_short(5040, 1)."\n"; //outputs 5K
  19. echo num_short(5400, 1)."\n"; //outputs 5.4K
  20. echo num_short(5900, 1)."\n"; //outputs 5.9K
  21. echo num_short(5990, 1)."\n"; //outputs 6K
  22. echo num_short(5999, 1)."\n"; //outputs 6K
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
5K
5K
5K
5.4K
5.9K
6K
6K