使用公制前缀(如1.5K,1M,1G等)格式化javascript编号

时间:2013-07-13 19:22:24

标签: javascript formatting

我想使用带有3位有效数字的Metric Prefix来显示数字,如下所示:

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函数来执行此操作,但我想知道是否有一种标准方式来格式化这样的数字?

1 个答案:

答案 0 :(得分:24)

您可以将范围放在一个对象数组中,然后循环遍历它以格式化数字:

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