Shorten long numbers to K/M/B?

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

    I took the answer BoltClock provided and tweaked it a bit with ease of configuration in mind.

    // Shortens a number and attaches K, M, B, etc. accordingly
    function number_shorten($number, $precision = 3, $divisors = null) {
    
        // Setup default $divisors if not provided
        if (!isset($divisors)) {
            $divisors = array(
                pow(1000, 0) => '', // 1000^0 == 1
                pow(1000, 1) => 'K', // Thousand
                pow(1000, 2) => 'M', // Million
                pow(1000, 3) => 'B', // Billion
                pow(1000, 4) => 'T', // Trillion
                pow(1000, 5) => 'Qa', // Quadrillion
                pow(1000, 6) => 'Qi', // Quintillion
            );    
        }
    
        // Loop through each $divisor and find the
        // lowest amount that matches
        foreach ($divisors as $divisor => $shorthand) {
            if (abs($number) < ($divisor * 1000)) {
                // We found a match!
                break;
            }
        }
    
        // We found our match, or there were no matches.
        // Either way, use the last defined value for $divisor.
        return number_format($number / $divisor, $precision) . $shorthand;
    }
    

提交回复
热议问题