php 将长数字缩短为 K/M/B?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4371059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:51:23  来源:igfitidea点击:

Shorten long numbers to K/M/B?

phpfunctionhelper

提问by Ryan

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!

谢谢!

回答by BoltClock

Use number_format():

使用number_format()

if ($n < 1000000) {
    // Anything less than a million
    $n_format = number_format($n);
} else if ($n < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($n / 1000000, 3) . 'M';
} else {
    // At least a billion
    $n_format = number_format($n / 1000000000, 3) . 'B';
}

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

如果可能的话,我非常感谢任何自定义函数来动态选择限制。

If "limit" refers to the number of decimal places (the precision), that's easy:

如果“限制”是指小数位数(精度),那很简单:

function custom_number_format($n, $precision = 3) {
    if ($n < 1000000) {
        // Anything less than a million
        $n_format = number_format($n);
    } else if ($n < 1000000000) {
        // Anything less than a billion
        $n_format = number_format($n / 1000000, $precision) . 'M';
    } else {
        // At least a billion
        $n_format = number_format($n / 1000000000, $precision) . 'B';
    }

    return $n_format;
}

回答by Kyle Challis

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

我接受了 BoltClock 提供的答案,并在考虑到易于配置的情况下对其进行了一些调整。

// 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;
}

回答by kjdion84

function number_abbr($number)
{
    $abbrevs = [12 => 'T', 9 => 'B', 6 => 'M', 3 => 'K', 0 => ''];

    foreach ($abbrevs as $exponent => $abbrev) {
        if (abs($number) >= pow(10, $exponent)) {
            $display = $number / pow(10, $exponent);
            $decimals = ($exponent >= 3 && round($display) < 100) ? 1 : 0;
            $number = number_format($display, $decimals).$abbrev;
            break;
        }
    }

    return $number;
}

Works for positives and negatives.

适用于正面和负面。

回答by Nivesh Saharan

<?php
// Converts a number into a short version, eg: 1000 -> 1k
// Based on: http://stackoverflow.com/a/4371114
function number_format_short( $n, $precision = 1 ) {
    if ($n < 900) {
        // 0 - 900
        $n_format = number_format($n, $precision);
        $suffix = '';
    } else if ($n < 900000) {
        // 0.9k-850k
        $n_format = number_format($n / 1000, $precision);
        $suffix = 'K';
    } else if ($n < 900000000) {
        // 0.9m-850m
        $n_format = number_format($n / 1000000, $precision);
        $suffix = 'M';
    } else if ($n < 900000000000) {
        // 0.9b-850b
        $n_format = number_format($n / 1000000000, $precision);
        $suffix = 'B';
    } else {
        // 0.9t+
        $n_format = number_format($n / 1000000000000, $precision);
        $suffix = 'T';
    }
  // Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
  // Intentionally does not affect partials, eg "1.50" -> "1.50"
    if ( $precision > 0 ) {
        $dotzero = '.' . str_repeat( '0', $precision );
        $n_format = str_replace( $dotzero, '', $n_format );
    }
    return $n_format . $suffix;
}
/*
Example Usage:
number_format_short(7201); // Output: 7.2k
Demo:
echo '<table>';
for($d = 0; $d < 16; $d++ ) {
    $n = intval("09" . str_repeat( "0", $d ));
    $n = $n / 10;
    echo number_format_short($n) .'<br>'; // 0.9
    $n = intval("1" . str_repeat( "0", $d ));
    echo number_format_short($n) .'<br>'; // 1.0
    $n = intval("11" . str_repeat( "0", $d ));;
    $n = $n / 10;
    echo number_format_short($n) .'<br>'; // 1.1
}
echo '</table>';
Demo Output:
0.9
1
1.1

9
10
11

90
100
110

0.9K
1K
1.1K

9K
10K
11K

90K
100K
110K

0.9M
1M
1.1M

9M
10M
11M

90M
100M
110M

0.9B
1B
1.1B

9B
10B
11B

90B
100B
110B

0.9T
1T
1.1T

9T
10T
11T

90T
100T
110T

900T
1,000T
1,100T
*/

回答by Clinton Canarias

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;
    }

回答by DreiDe

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.

我希望它仍然对某人有帮助。

回答by reformed

Try this. Accounts for the groups k, M, B, T, and Q (quadrillion). Anything higher than 999Q shows as 999Q+.

尝试这个。说明组 k、M、B、T 和 Q(千万亿)。任何高于 999Q 的值都显示为 999Q+。

function number($num, $precision = 2)
{
    $absNum = abs($num);

    if ($absNum < 1000)
    {
        return (string)round($num, $precision);
    }

    $groups = ['k','M','B','T','Q'];

    foreach ($groups as $i => $group)
    {
        $div = 1000 ** ($i + 1);

        if ($absNum < $div * 1000)
        {
            return round($num / $div, $precision) . $group;
        }
    }

    return '999Q+';
}

回答by Manu

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;
    }

回答by Stephen

CakePHP has a Number Helperwith a method toReadableSize. You should be able to grok it and come up with something on your own. In it, $this->precisionis basically like number_format(), and __nis a singular-or-plural function.

CakePHP 有一个带有方法的数字助手toReadableSize。你应该能够理解它并自己想出一些东西。在其中,$this->precision基本上就像number_format(),并且__n是单数或复数的函数。