Format Numbers in PHP ( like 1.2K, 3.1M, 2.5B )

We normally see huge number in formats like 1.2K, 3.1M and 2.5B. Its not practicable to write large numbers in full numbers like 1200000 or 2200000000.

In this post, we will be writing a PHP function to format a number in the short form.

<?php 
    function format_number($number) {
        // first strip any formatting;
        $number = (0+str_replace(",", "", $number));
 
        // is this a number?
        if (!is_numeric($number)) return false;
 
        // now filter it;
        if ($number > 1000000000000) return round(($number/1000000000000), 2).'T';
        elseif ($number > 1000000000) return round(($number/1000000000), 2).'B';
        elseif ($number > 1000000) return round(($number/1000000), 2).'M';
        elseif ($number > 1000) return round(($number/1000), 2).'K';
 
        return number_format($n);
    }
 
echo format_number('8700000');
echo format_number('53420');
?>

Refer this video for complete guidance :



Recommended For You

About the Author: Admin