Какой самый быстрый способ взять большие числа (например, 1900234) и поставить запятые после каждых трех цифр? - PullRequest
0 голосов
/ 26 ноября 2018

Я работаю над проектом стажировки, который, хотя он и не сфокусирован на производительности, хотел бы быть настолько быстрым (и скудным), насколько это возможно.Пока у меня есть одна рабочая версия (с ошибкой) и одна концепция вышеупомянутой функции:

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 Concept (выглядит медленнее, но ошибок нет)

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 голосов
/ 26 ноября 2018

Попробуйте это

var str = "123456789";
var result = [...str].map((d, i) => i % 3 == 0 && i > 0 ? ','+d : d).join('').trim();
console.log(result);
0 голосов
/ 26 ноября 2018

Проверьте функцию toLocaleString:

const b = 5120312039;
console.log(b.toLocaleString()); //"5,120,312,039"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...