在JavaScript中显示带有显着数字和K / M / B / T后缀的数字

时间:2014-08-21 00:43:20

标签: javascript number-formatting

我想要一个JavaScript函数将数字转换为带有后缀的重要数字。例如,12,345可以返回12.3K,而1,000,000可以返回1.00M

1 个答案:

答案 0 :(得分:1)

查看此功能和相关测试,也在this Apps Script file容器绑定到this spreadsheet中实现:

// Calculates significant figures with suffixes K/M/B/T, e.g. 1234 = 1.23K
function sigfig(num, sigfigs_opt) {
  // Set default sigfigs to 3
  sigfigs_opt = (typeof sigfigs_opt === "undefined") ? 3 : sigfigs_opt;
  // Only assigns sig figs and suffixes for numbers > 1
  if (num <= 1) return num.toPrecision(sigfigs_opt);
  // Calculate for numbers > 1
  var power10 = log10(num);
  var power10ceiling = Math.floor(power10) + 1;
  // 0 = '', 1 = 'K', 2 = 'M', 3 = 'B', 4 = 'T'
  var SUFFIXES = ['', 'K', 'M', 'B', 'T'];
  // 100: power10 = 2, suffixNum = 0, suffix = ''
  // 1000: power10 = 3, suffixNum = 1, suffix = 'K'
  var suffixNum = Math.floor(power10 / 3);
  var suffix = SUFFIXES[suffixNum];
  // Would be 1 for '', 1000 for 'K', 1000000 for 'M', etc.
  var suffixPower10 = Math.pow(10, suffixNum * 3);
  var base = num / suffixPower10;
  var baseRound = base.toPrecision(sigfigs_opt);
  return baseRound + suffix;
}

function log10(num) {
  // Per http://stackoverflow.com/questions/3019278/how-can-i-specify-the-base-for-math-log-in-javascript#comment29970629_16868744
  // Handles floating-point errors log10(1000) otherwise fails at (2.99999996)
  return (Math.round(Math.log(num) / Math.LN10 * 1e6) / 1e6);
}

// Tests for sigfig(num, sigfigs=3). Returns T/F indicating test pass/fail.
function sigfig_test() {
  if (sigfig(1) != '1.00') return false;
  if (sigfig(1, 2) != '1.0') return false;
  if (sigfig(1.2) != '1.20') return false;
  if (sigfig(1234.5) != '1.23K') return false;
  if (sigfig(1000) != '1.00K') return false;
  if (sigfig(1234567) != '1.23M') return false;
  if (sigfig(1234567890, 4) != '1.235B') return false;
  if (sigfig(1e12, 1) != '1T') return false;
  if (sigfig(0.999999) != '1.00') return false;
  if (sigfig(0.00000434, 2) != '0.0000043') return false;
  return true;
}