首页 > 解决方案 > 取大数字(例如1900234)并在每三位数字后加逗号的最快方法是什么?

问题描述

我正在做一个实习项目,虽然它不关注绩效,但我希望尽可能快(和精益)。到目前为止,我有一个工作版本(有一个错误)和一个上述功能的概念:

V1(BUG:无法处理带点和逗号的数字。)

function addCommas(nStr) {
  if (isNaN(nStr)) {
    throw new Error(`${nStr} is NaN`);
  }
  // Alternative: isNaN(nStr) ? throw new Error(`${nStr} is NaN`) : nStr += ``;
  nStr += ``;
  // If the input is of the form 'xxxx.yyy', split it into x1 = 'xxxx'
  // and x2 = '.yyy'.
  let x = nStr.split(`.`);
  let x1 = x[0];
  let x2 = x.length > 1 ? `.` + x[1] : ``;
  let rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    // x1 takes the form 'x,xxx' - no matter how long the number,
    // this is where the commas are added after every three digits.
    x1 = x1.replace(rgx, `$1` + `,` + `$2`);
  }
  return x1 + x2;
}

V2 概念(看起来较慢但没有已知错误)

function addCommas(nStr) {
  if (isNaN(nStr)) {
    throw new Error(`${nStr} is NaN`);
  }
  nStr += ``;
  // Remove any potential dots and commas.
  nStr = nStr.replace(`.`, ``);
  nStr = nStr.replace(`,`, ``);
  // Split the number into an array of digits using String.prototype.split().
  // Iterate digits. After every three, add a comma.
  // Transform back into a string.
  return nStr;
}

标签: javascriptperformance

解决方案


查看函数 toLocaleString:

const b = 5120312039;
console.log(b.toLocaleString()); //"5,120,312,039"

推荐阅读