Format echo number with 'k', 'kk', and so on

4

In several places on the internet you can view number formatting such as "150k", "1kk". Most people know that 150k is 150,000 and 1kk is 1,000,000.

EXAMPLE:

ThatwouldbeusefulbecausesometimesImovewithbignumbers,whichaestheticallyisbad,becausesometimesitgoesbeyondlimits!Withthiskindofformattingthenumberwouldalwaysbesummarized.

Iwouldlikethisformattingtostartfromthefirst"1,000" which would soon be "1k", I would also like the number to always be rounded up and not down.

Formatting examples:

10             =  10
100            =  100
999            =  999

1.000          =  1k
1.499          =  1k
1.501          =  2k
10.000         =  10k
100.000        =  100k

1.000.000      =  1kk
10.000.000     =  10kk
100.000.000    =  100kk

1.000.000.000  =  10kkk

I'd like to know how to do this at the time of echo .

    
asked by anonymous 18.02.2015 / 04:33

2 answers

12

Here's your function:

function reduz_numero($n) {
    if ($n < 0) return "-" . reduz_numero(-$n);
    $k = "";
    while (round($n) >= 1000) {
        $k = $k . "k";
        $n = $n / 1000;
    }
    return round($n) . $k;
}

Some tests with it, using echo :

echo "         5->" . reduz_numero(         5) . "\n"; // Mostra "5"
echo "       999->" . reduz_numero(       999) . "\n"; // Mostra "999"
echo "      1000->" . reduz_numero(      1000) . "\n"; // Mostra "1k"
echo "      1001->" . reduz_numero(      1001) . "\n"; // Mostra "1k"
echo "      1499->" . reduz_numero(      1499) . "\n"; // Mostra "1k"
echo "      1500->" . reduz_numero(      1500) . "\n"; // Mostra "2k"
echo "      1501->" . reduz_numero(      1501) . "\n"; // Mostra "2k"
echo "     10000->" . reduz_numero(     10000) . "\n"; // Mostra "10k"
echo "    999499->" . reduz_numero(    999499) . "\n"; // Mostra "999k"
echo "    999500->" . reduz_numero(    999500) . "\n"; // Mostra "1kk"
echo "    999501->" . reduz_numero(    999501) . "\n"; // Mostra "1kk"
echo "1000000000->" . reduz_numero(1000000000) . "\n"; // Mostra "1kkk"
echo "    -77777->" . reduz_numero(    -77777) . "\n"; // Mostra "-78k"
echo "   9499999->" . reduz_numero(   9499999) . "\n"; // Mostra "9kk"
echo "   9500000->" . reduz_numero(   9500000) . "\n"; // Mostra "10kk"

See working on ideone.

EDIT: Now it also works with negative numbers. : EDIT 2: Bugfix for 9499999, was showing "10kk" instead of "9kk". >     

18.02.2015 / 09:59
3

I've never written anything in php, so it's unlikely to work ...

function reduz($n) {
    $n=floor($n);
    if ($n      < 1000) return $n;
    if ($n%1000 <  500) return reduz(  $n/1000). "k"
    if ($n%1000 >= 500) return reduz(1+$n/1000). "k";
}
    
18.02.2015 / 16:07