Tuesday 19 November 2019

How to Convert 1,000 to 1k using PHP

Here's a generic way to do this that doesn't require you to use number_format or do string parsing:


function formatWithSuffix($input)
{
    $suffixes = array('', 'k', 'm', 'g', 't');
    $suffixIndex = 0;

    while(abs($input) >= 1000 && $suffixIndex < sizeof($suffixes))
    {
        $suffixIndex++;
        $input /= 1000;
    }

    return (
        $input > 0
            // precision of 3 decimal places
            ? floor($input * 1000) / 1000
            : ceil($input * 1000) / 1000
        )
        . $suffixes[$suffixIndex];
}

echo formatWithSuffix(1000);
echo formatWithSuffix(100000); 

Let me know if I missed any of your requirements:












Previous Post
Next Post

post written by:

0 Comments:

Hit me with a comment!