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.
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
Instead of intval(), use number_format() to give you a number with the desired amount of decimal places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With