Shorten long numbers to K/M/B?

2020-01-24 20:48发布

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,840

BUT

2023150 -> 2.023M ( i still want 3 additional numbers for more accuracy )
5430120215 -> 5.430B

I would totally appreciate any custom functions to dynamically choose the limit if possible.

Thanks!

9条回答
祖国的老花朵
2楼-- · 2020-01-24 21:15

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;
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-24 21:23

Try this

function custom_number_format($n, $precision = 1) {
        if ($n < 900) {
        // Default
         $n_format = number_format($n);
        } else if ($n < 900000) {
        // Thausand
        $n_format = number_format($n / 1000, $precision). 'K';
        } else if ($n < 900000000) {
        // Million
        $n_format = number_format($n / 1000000, $precision). 'M';
        } else if ($n < 900000000000) {
        // Billion
        $n_format = number_format($n / 1000000000, $precision). 'B';
        } else {
        // Trillion
        $n_format = number_format($n / 1000000000000, $precision). 'T';
    }
    return $n_format;
    }
查看更多
劳资没心,怎么记你
4楼-- · 2020-01-24 21:24

You can try this

 function number_formation($number, $precision = 3) {
        if ($number < 1000000) {

            $formatted_number = number_format($number); /* less than a million */
        } else if ($number < 1000000000) {

            $formatted_number = number_format($number / 1000000, $precision) . 'M'; /* billion */
        } else {

            $formatted_number = number_format($number  / 1000000000, $precision) . 'B'; /* for billion */
        }

        return $formatted_number;
    }
查看更多
登录 后发表回答