gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:54:28 27 4
gpt4 key购买 nike

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

我想要的是:

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

关于php - 将长数字缩短为 K/M/B?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4371059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com