Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP number abbreviator

Edit: Function below now does the abbreviation correctly, implemented @Asad 's solution

Hi I am currently working on a like button, I've got all the base functionality working nicely however I have started the number abbreviation code and hit a wall as I can't figure out how to make the abbreviation more precise.

I have a number, e.g. 1000, 1230, 1500, 154000, 1500000, 1000000

And I want to format them with an abbreviation. i.e.

if it's a thousand, then 1k, 1.1k, 2k, 10k, 10.5k etc...

and so on for the tens, hundreds thousands and millions, etc...

At the moment I have the following function but it's not specific enough:

function abreviateTotalCount($value) 
{

    $abbreviations = array(12 => 'T', 9 => 'B', 6 => 'M', 3 => 'K', 0 => '');

    foreach($abbreviations as $exponent => $abbreviation) 
    {

        if($value >= pow(10, $exponent)) 
        {

            return round(floatval($value / pow(10, $exponent))).$abbreviation;

        }

    }

}

Thanks in advance!

like image 703
André Figueira Avatar asked Oct 24 '12 13:10

André Figueira


3 Answers

If you want to keep the decimal places, use floatval instead of intval:

return round(floatval($value / pow(10, $exponent)),1).$abbreviation;

gets the float representation and rounds to 1 decimal place.

like image 121
Asad Saeeduddin Avatar answered Nov 17 '22 13:11

Asad Saeeduddin


check that project https://github.com/gburtini/Humanize-PHP/blob/master/Humanize.php

php > echo HumanizePHP::intword(256,0,0);
3 hundred
php > echo HumanizePHP::intword(256,0,1);
2.6 hundred
php > echo HumanizePHP::intword(256,0,2);
2.56 hundred

At least you can take idea from this implementation

like image 2
Fivell Avatar answered Nov 17 '22 13:11

Fivell


Instead of intval(), use number_format() to give you a number with the desired amount of decimal places.

like image 1
bobwienholt Avatar answered Nov 17 '22 12:11

bobwienholt