How to abbreviate/format php numbers, as on Youtube?

Asked

Viewed 44 times

0

Ex: 10000 turns 10k, 1000000 turns 1M and so on?

Well, I did it this way. If anyone has a better and more practical way, please let me know:

function abrevNmr($numero){     
        switch(strlen($numero)){
            case 1:
            case 2:
            case 3:
                    return $numero;
                break;
            case 4: 
                    $num = str_split($numero, 1);
                    return $num[0].($num[1] > 0 ? ','.$num[1] : null).'k';
                break;
            case 5:
                    $num = str_split($numero, 1);
                    return $num[0].$num[1].($num[2] > 0 ? ','.$num[2] : null).'k';
                break;
            case 6:
                    $num = str_split($numero, 1);
                    return $num[0].$num[1].$num[2].($num[3] > 0 ? ','.$num[3] : null).'k';
                break;
            case 7:
                    $num = str_split($numero, 1);
                    return $num[0].($num[1] > 0 ? ','.$num[1] : null).'mi';
                break;
            case 8:
                    $num = str_split($numero, 1);
                    return $num[0].$num[1].($num[2] > 0 ? ','.$num[2] : null).'mi';
                break;
        }
    }

It goes up to 99 million, because that’s more than enough for what I want.

  • what is the full rule? 10000 turns 10k, okay, but and 10896, still 10k? or turn 11? 10.5? what if it’s 1,960,526.23? Is it 1M? 2M? 1,96M?

  • Beyond the top link, here also has a similar case, and this answer also shows the logic that does this (only in js)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.