我想使用具有 3 个有效数字的度量前缀显示数字,如下所示:
1 shows as 1
999 shows as 999
1000 shows as 1K
999000 shows as 999K
1000000 shows as 1M
1500000 shows as 1.5M
1000000000 shows as 1G
etc...
我可以编写自己的 javascript 函数来做到这一点,但我想知道是否有一种标准的方式来格式化这样的数字?
我想使用具有 3 个有效数字的度量前缀显示数字,如下所示:
1 shows as 1
999 shows as 999
1000 shows as 1K
999000 shows as 999K
1000000 shows as 1M
1500000 shows as 1.5M
1000000000 shows as 1G
etc...
我可以编写自己的 javascript 函数来做到这一点,但我想知道是否有一种标准的方式来格式化这样的数字?
您可以将范围放在对象数组中,然后循环遍历它以格式化数字:
var ranges = [
{ divider: 1e18 , suffix: 'E' },
{ divider: 1e15 , suffix: 'P' },
{ divider: 1e12 , suffix: 'T' },
{ divider: 1e9 , suffix: 'G' },
{ divider: 1e6 , suffix: 'M' },
{ divider: 1e3 , suffix: 'k' }
];
function formatNumber(n) {
for (var i = 0; i < ranges.length; i++) {
if (n >= ranges[i].divider) {
return (n / ranges[i].divider).toString() + ranges[i].suffix;
}
}
return n.toString();
}
使用示例:
var s = formatNumber(999000);
要同时处理负数,您将首先在函数中添加:
if (n < 0) {
return '-' + formatNumber(-n);
}