一尘不染

缩短长号到K / M / B吗?

php

我已经在Google上进行了很多搜索,但根据查询找不到任何有用的功能。

我想要的是:

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

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

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

谢谢!


阅读 365

收藏
2020-05-29

共1个答案

一尘不染

用途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';
}

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

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

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;
}
2020-05-29