Shorten long numbers to K/M/B?

前端 未结 10 1868
南方客
南方客 2020-11-27 03:39

I\'ve googled this a lot but i can\'t find any helpful functions based on my queries.

What i want is:

100 -> 100
1000 -> 1,000
142840 -> 142         


        
10条回答
  •  有刺的猬
    2020-11-27 04:11

    I took a different approach based on the previous solutions. Basically it uses the log() function to get rid of the for statement:

    function number_shorten($number, $precision = 3)
    {
        $suffixes = ['', 'K', 'M', 'B', 'T', 'Qa', 'Qi'];
        $index = (int) log(abs($number), 1000);
        $index = max(0, min(count($suffixes) - 1, $index)); // Clamps to a valid suffixes' index
        return number_format($number / 1000 ** $index, $precision) . $suffixes[$index];
    }
    

提交回复
热议问题