高级前端手写代码【Q594】给数字添加千位符

给数字添加千位符

更多描述

//=> '123'
numberThousands(123);
 
//=> '1,234,567'
numberThousands(1234567);

问题追问:

  • 如果考虑正负数应该如何处理
  • 如果考虑小数应该如何处理?
//=> '123'
numberThousands(123);
 
//=> '1,234,567'
numberThousands(1234567);
 
// 可以处理正负数
// => '-123,456'
numberThousands(123456);
 
// 可以处理小数
// => '-123,456.123456789'
numberThousands(123456.123456789);

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 610

Author 回答者: shfshanyue

千位符替换可由正则 /(\d)(?=(\d\d\d)+(?!\d))/ 进行匹配

function numberThousands(number, thousandsSeperator = ",") {
  return String(number).replace(
    /(\d)(?=(\d\d\d)+(?!\d))/g,
    "$1" + thousandsSeperator,
  );
}

删除的正则或许有点复杂,如果对字符串反转,可以来一个简单的正则

function numberThousands(number, thousandsSeperator = ",") {
  const reverse = (str) => str.split("").reverse().join("");
  const str = reverse(String(number)).replace(
    /(\d\d\d)(?=\d)/g,
    "$1" + thousandsSeperator,
  );
  return reverse(str);
}

如果你写不出来正则,也可由一段简单的代码实现

function numberThousands(number, thousandsSeperator = ",") {
  const s = String(number);
  let r = "";
  for (let i = s.length - 1; i >= 0; i--) {
    const seperator = (s.length - i - 1) % 3 ? "" : thousandsSeperator;
    r = `${s[i]}${seperator}${r}`;
  }
  return r.slice(0, -1);
}

同时,再提供一个取巧的办法:

Intl.NumberFormat(undefined, {
  style: "decimal",
  maximumFractionDigits: 20,
}).format(number);
 
number.toLocaleString(undefined, { maximumFractionDigits: 20 });

Author 回答者: haotie1990

如果你写不出来正则,也可由一段简单的代码实现

function toString(number, thousandsSeperator = ",") {
  const s = String(number);
  let r = "";
  for (let i = s.length - 1; i >= 0; i--) {
    const seperator = (s.length - i - 1) % 3 ? "" : thousandsSeperator;
    r = `${s[i]}${seperator}${r}`;
  }
  return r.slice(0, -1);
}

这个有点问题,如果是带有小数的数字,会有转换异常

Author 回答者: Asarua

function toString(number) {
  return number.toLocaleString();
}

哈哈哈哈,取个巧

Author 回答者: haotie1990

function numberThousands(number) {
  const numberStr = String(number);
  let result = "";
  let [interger, decimal] = numberStr.split(".");
  while (interger.length > 3) {
    // 倒数三位数字
    let subStr = interger.substring(interger.length - 3);
    interger = interger.replace(subStr, "");
    result = `,${subStr}${result}`;
  }
  if (interger.length) {
    result = `${interger}${result}`;
  }
  return result + (decimal ? `.${decimal}` : "");
}

Author 回答者: VirgoHxy

function numberThousands(num) {
  let result = "";
  let str = String(num);
  let length = str.length;
  for (let index = length - 1; index >= 0; index--) {
    const element = str[index];
    result = element + result;
    if (index && (length - index) % 3 == 0) {
      result = "," + result;
    }
  }
  return result;
}

Author 回答者: bigbigDreamer

const numberThousands = (number) => {
  const strNum = Number.parseFloat(number).toString();
  const [interSection, restSection] = strNum.split(".");
  const reverseInter = interSection.split("").reverse().join("");
 
  const finalInter = reverseInter
    .match(/(\d{0,3})+?/g)
    .filter((x) => x)
    .map((item) => item.split("").reverse().join(""))
    .reverse()
    .join(",");
 
  return `${finalInter}${restSection ? `.${restSection}` : ""}`;
};

Author 回答者: okkjoo

删除的正则或许有点复杂,如果对字符串反转,可以来一个简单的正则

function numberThousands(number, thousandsSeperator = ",") {
  const reverse = (str) => str.split("").reverse().join("");
  const str = reverse(String(number)).replace(
    /\d\d\d(?!\d)/g,
    "$1" + thousandsSeperator,
  );
  return reverse(str);
}
错了,应该是 ?= 而不是 ?!
```js
function numberThousands(number, thousandsSeperator = ",") {
  const reverse = (str) => str.split("").reverse().join("");
  const str = reverse(String(number)).replace(
    /(\d\d\d)(?=\d)/g,
    "$1" + thousandsSeperator
  );
  return reverse(str);
}