Shorten long numbers to K/M/B?

前端 未结 10 2267
南方客
南方客 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:05

    Altough this question was asked quite some time ago I have a different solution, which I think is even more simple:

    function shorten($number){
        $suffix = ["", "K", "M", "B"];
        $precision = 1;
        for($i = 0; $i < count($suffix); $i++){
            $divide = $number / pow(1000, $i);
            if($divide < 1000){
                return round($divide, $precision).$suffix[$i];
                break;
            }
        }
    }
    echo shorten(1000);
    

    I hope that it's still helpful for someone.

提交回复
热议问题