Format Shorten Number to Readable 1000 to 1k

Sovary July 1, 2022 689
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him