将长号缩短为K / M / B? [英] Shorten long numbers to K/M/B?
问题描述
我想要的是:
$ b我已经使用了很多搜索引擎,但是找不到任何有用的函数。$ b
100 - > 100
1000 - > 1,000
142840 - > 142,840
2023150 - > 2.023M(为了更高的准确性,我还需要3个数字)
5430120215 - > 5.430B
我会完全赞赏任何自定义函数,如果可能的话动态选择限制。
谢谢!
number_format() code $:
$ $ p $ if($ n <1000000){
//任何小于一百万
$ n_format = number_format($ n);
} else if($ n <1000000000){
//小于十亿
$ n_format = number_format($ n / 1000000,3)。 M;
} else {
//至少十亿
$ n_format = number_format($ n / 1000000000,3)。 B;
}
我会完全理解任何自定义函数的动态如果可能,请选择限制。
如果限制是指小数位数(精度),那很简单:($ n< 1000000){$ b $(
$ $ p $ b //小于一百万美元b $ b $ n_format = number_format($ n);
} else if($ n <1000000000){
//小于十亿
$ n_format = number_format($ n / 1000000,$ precision)。 M;
} else {
//至少十亿
$ n_format = number_format($ n / 1000000000,$ precision)。 B;
}
返回$ n_format;
}
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!
解决方案 Use 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;
}
这篇关于将长号缩短为K / M / B?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!