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!
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.