Convert Number into Sort Number Format In PHP (Eg: 1.2K, 15.10M, 20B etc)

If you want to convert any number into sort form in thousand, million, billion then in this post we have shared simple php function to convert any number to it’s sort form. Like you have price list data and you don’t want to display full price amount in number form then you can simply pass value into below function and it’ll convert you price amount to sort form like (Eg: 1.2K, 15.10M, 20B ) etc.

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.