convert number

How to abbreviate numbers in PHP

This post has been viewed 103 times.

In this tutorial, we would be using a PHP function to abbreviate numbers in PHP. This will convert big numbers such as 1000 to 1K, 1000000 to 1M and so on. This will support up to trillions of numbers.

Do you want to have a shorter version of numbers as seen on the famous website such as YouTube where you notice that their number of views is abbreviated? This is the tutorial for you.

Step 1: Create your PHP function that accepts a parameter.

This is a PHP function that accepts a value.

Step 2: Create a condition for each group.

In this tutorial, I would group the numbers in thousands, millions, billions and trillions. If ever you need a number bigger than trillions you can just simply add another condition.

If the number is between 0 to 999, I would just simply display the number as it is.

But if the number ranges from 1,000 to 999,999 where 999,999 is the last number to be included in the thousands group. I will use the suffix K for thousands.

You will also do this for the other groups.

Step 4: Return the abbreviated number.

This will now return the abbreviated number of the number that is received in the parameter.

Complete code:

Basic usage:

This will be the output of the following input where the output is commented on each line.

That’s it, we have now created a PHP function that will allow us to convert big numbers to the abbreviated one.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.