Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show 1k instead of 1,000

    function restyle_text($input){
    $input = number_format($input);
    $input_count = substr_count($input, ',');
    if($input_count != '0'){
        if($input_count == '1'){
            return substr($input, +4).'k';
        } else if($input_count == '2'){
            return substr($input, +8).'mil';
        } else if($input_count == '3'){
            return substr($input, +12).'bil';
        } else {
            return;
        }
    } else {
        return $input;
    }
}

This is the code I have, I thought it was working. apparently not.. can someone help since I can't figure this out.

like image 701
Jake Avatar asked Dec 18 '11 02:12

Jake


3 Answers

Try this:

http://codepad.viper-7.com/jfa3uK

function restyle_text($input){
    $input = number_format($input);
    $input_count = substr_count($input, ',');
    if($input_count != '0'){
        if($input_count == '1'){
            return substr($input, 0, -4).'k';
        } else if($input_count == '2'){
            return substr($input, 0, -8).'mil';
        } else if($input_count == '3'){
            return substr($input, 0,  -12).'bil';
        } else {
            return;
        }
    } else {
        return $input;
    }
}

Basically, I think you're using the substr() wrong.

like image 118
Indranil Avatar answered Oct 04 '22 06:10

Indranil


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];
}

And here's a demo showing it working correctly for several cases.

like image 32
Merlyn Morgan-Graham Avatar answered Oct 04 '22 06:10

Merlyn Morgan-Graham


I re-wrote the function to use the properties of numbers rather than playing with strings.

That should be faster.

Let me know if I missed any of your requirements:

function restyle_text($input){
    $k = pow(10,3);
    $mil = pow(10,6);
    $bil = pow(10,9);

    if ($input >= $bil)
        return (int) ($input / $bil).'bil';
    else if ($input >= $mil)
        return (int) ($input / $mil).'mil';
    else if ($input >= $k)
        return (int) ($input / $k).'k';
    else
        return (int) $input;
}
like image 26
Dimme Avatar answered Oct 04 '22 05:10

Dimme