将长数字缩短为 K/M/B? [英] Shorten long numbers to K/M/B?
本文介绍了将长数字缩短为 K/M/B?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在谷歌上搜索了很多,但根据我的查询我找不到任何有用的功能.
我想要的是:
100 ->1001000 ->1,000142840 ->142,840
但是
2023150 ->2.023M(为了更准确,我还需要 3 个额外的数字)5430120215 ->5.430B
如果可能,我非常感谢任何自定义函数来动态选择限制.
谢谢!
解决方案
使用 number_format()
:
if ($n <1000000) {//小于一百万$n_format = number_format($n);} else if ($n <1000000000) {//任何小于十亿$n_format = number_format($n/1000000, 3) .'M';} 别的 {//至少十亿$n_format = number_format($n/1000000000, 3) .'乙';}
<块引用>
如果可能,我非常感谢任何自定义函数来动态选择限制.
如果限制"是指小数位数(精度),那很简单:
function custom_number_format($n, $precision = 3) {如果 ($n <1000000) {//小于一百万$n_format = number_format($n);} else if ($n <1000000000) {//任何小于十亿$n_format = number_format($n/1000000, $precision) .'M';} 别的 {//至少十亿$n_format = number_format($n/1000000000, $precision) .'乙';}返回 $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屋!
查看全文