取大数字(例如1900234)并在每三位数后加逗号的斋戒方式是什么?

时间:2018-11-26 09:01:11

标签: javascript performance

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

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

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

2 个答案:

答案 0 :(得分:2)

签出函数toLocaleString:

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

答案 1 :(得分:0)

尝试一下

var str = "123456789";
var result = [...str].map((d, i) => i % 3 == 0 && i > 0 ? ','+d : d).join('').trim();
console.log(result);