Format Shorten Number to Readable 1000 to 1k

Sovary July 1, 2022 522
1 minute read

Hi my friends, today we will show you how to format any number length to K/M/B which are 1,000 to 1K or 1,000,000 to 1M. These formats you might see in YouTube to show either subscriber or view count. With various method below will help you to convert those number to shorten number and you can apply in Laravel or other platforms which support PHP.

thumbnial_php_Format_Shorten_Number-1000-to-1K

Input

100
1245
654514
1473254

Output

100
1.24k
654.51k
1.47m

We have two solutions to apply with your project. Which one is best implementation for you?

Solution #1 - Convert Raw Number to Short Number

<?php

function format($num) 
{
  $b = pow(1000,3);
  $m = pow(1000,2);
  $k = pow(1000,1);
  if($num >=$b)
  {
    return round($num/$b,2) . "b";
  }
  else if($num >= $m)
  {
    return round($num/$m,2) . "m";
  }
  else if($num >= $k)
  {
    return round($num/$k,2) ."k";
  }
  return $num;
}

echo format(110140);
echo "\n".format(1354014);

?>

Output #1

110.14k
1.35m

Solution #2 - Convert Raw Number to Short Number

<?php

function format($number) 
{
  if($number < 1) return 0;
   $divisors = [
     pow(1000, 0) => '', 
     pow(1000, 1) => 'k',
     pow(1000, 2) => 'm',
     pow(1000, 3) => 'b'
    ];
  foreach ($divisors as $divisor => $shorthand) 
  {
      if ($number < ($divisor * 1000)) break;
  }
  return round($number / $divisor,2) . $shorthand;
}
echo format(29440);
echo "\n".format(1312394);
?>

Output #2

29.44k
1.31m

If you required more then billion number, you can add more ordering by sequence amount.

Thanks for read my article, hope it would help your project. Have a nice day!

PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him