Sling Academy
Home/PHP/PHP: Formatting thousand, million as K, M (e.g. 1k, 2m)

PHP: Formatting thousand, million as K, M (e.g. 1k, 2m)

Last updated: January 09, 2024

Overview

When dealing with large numbers on websites and applications, it’s often more readable to format thousands and millions as ‘K’ for thousand and ‘M’ for million. This tutorial will walk you through how to implement this in PHP with practical code examples.

Understanding Number Abbreviation

Before diving into the specifics of formatting numbers in PHP, it’s important to understand what we mean by ‘abbreviated number formatting’. This is the process of converting a full number, such as 1500, into a more compact form, like ‘1.5K’. This is commonly used in social media platforms for displaying follower counts, in financial reports for denoting currency amounts, and in various other digital interfaces where space is at a premium.

Basic PHP Function for Number Abbreviation

In the following example, we’ll define a function named format_number that can help us get the job done in general scenarios:

<?php

function format_number($num) {
    if($num>=1000 && $num<1000000) {
        return round($num/1000, 1).'K';
    } else if($num>=1000000) {
        return round($num/1000000, 1).'M';
    } else {
        return $num;
    }
}

echo format_number(1500); // Outputs: 1.5K
echo format_number(2000000); // Outputs: 2M

?>

Improved Function with Dynamic Scaling

While the above function works well for thousands and millions, what about numbers in the billions or beyond? The following function dynamically scales based on the size of the number:

<?php

function abbreviate_number($num) {
    if($num >= 1000) {
        $units = array('', 'K', 'M', 'B', 'T');
        $log = floor(log($num, 1000));
        $pow = pow(1000, $log);
        return round($num / $pow, 2) . $units[$log];
    } else {
        return $num;
    }
}

echo abbreviate_number(1500); // Outputs: 1.5K
echo abbreviate_number(2000000); // Outputs: 2M

echo abbreviate_number(3400000000); // Outputs: 3.4B

?>

Handling Decimals and Rounding

Dealing with decimals requires a more nuanced approach as you may not always want to round to a certain number of decimal places. Here’s an example:

<?php

function format_number_precise($num, $precision=1) {
    $units = array('', 'K', 'M', 'B', 'T');
    $log = 0;
    if($num>=1000) {
        $log = floor(log($num, 1000));
    }
    $pow = pow(1000, $log);
    return round($num / $pow, $precision) . $units[$log];
}

echo format_number_precise(1550, 2); // Outputs: 1.55K

?>

Integrating into WebPages and Applications

Incorporating the number abbreviation into webpages and applications typically involves using the formatting functions in conjunction with dynamic data sources. For instance, when displaying user follower counts or financial data, the formatted number is called in real-time to keep the information accurate and readable.

Conclusion

In conclusion, formatting numbers as ‘K’ for thousands and ‘M’ for millions–and beyond–can significantly improve the user experience by making large numbers more digestible. By using PHP functions like those demonstrated in this tutorial, developers can easily integrate this functionality into their websites and applications. Keeping the formatting dynamic ensures that your application remains scalable and accurate regardless of the magnitude of the numbers involved.

Next Article: PHP: 4 Ways to Check if a Number is in a Range

Previous Article: PHP: Checking if a Number is Odd or Even

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array