使用 1.5K、1M、1G 等公制前缀格式化 javascript 数字
我想使用 Metric Prefix 显示数字,其中包含 3 个有效数字,如下所示:
I want to display numbers using a Metric Prefix with 3 significant digits like so:
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 函数来执行此操作,但我想知道是否有一种标准的方式来格式化这样的数字?
I could write my own javascript function to do this but I was wondering if there is a standard way of formatting numbers like this?
推荐答案
您可以将范围放在对象数组中,然后循环遍历它以格式化数字:
You can put the ranges in an array of objects, and just loop through it to format the number:
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);
要处理负数,您可以先在函数中添加:
To also handle negative numbers, you would add this first in the function:
if (n < 0) {
return '-' + formatNumber(-n);
}
相关文章