加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 将长号码缩短到K / M / B?

发布时间:2020-12-13 16:26:23 所属栏目:PHP教程 来源:网络整理
导读:我已经google了很多,但我找不到任何有用的功能,基于我的查询. 我想要的是: 100 - 1001000 - 1,000142840 - 142,840 但 2023150 - 2.023M ( i still want 3 additional numbers for more accuracy )5430120215 - 5.430B 我会非常感谢任何自定义的功能,以动态
我已经google了很多,但我找不到任何有用的功能,基于我的查询.

我想要的是:

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

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

我会非常感谢任何自定义的功能,以动态选择限制,如果可能的话.

谢谢!

使用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.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读