mortal-cultivation-biography / daydayup

A FE interview-questions collection repo.
8 stars 0 forks source link

实现金额的千位分隔 #30

Open nmsn opened 1 year ago

nmsn commented 1 year ago

如题,实现多种方式

nmsn commented 1 year ago
new Intl.NumberFormat().format(111111111.111)
// '111,111,111.111'
nmsn commented 1 year ago
const number = 123456.789;
number.toLocaleString(); // '123,456.789'
nmsn commented 1 year ago
function thousandsSeparator(n: number): string {
  const strSplit = n.toString().split(".");
  const integer = strSplit[0].split("");
  integer.reverse();
  const decimal = strSplit[1];
  const newInteger = [];
  for (let i = 0; i < integer.length; i++) {
    if (i % 3 === 0 && i !== 0) {
      newInteger.push(",");
    }
    newInteger.push(integer[i]);
  }
  newInteger.reverse();
  let s = newInteger.join("");
  if (decimal) {
    s += `.${decimal}`;
  }
  return s;
}
nmsn commented 1 year ago
function thousandsSeparator2(n: number): string {
  const strSplit = n.toString().split(".");
  const integer = strSplit[0];
  const decimal = strSplit[1] || "";
  return integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + decimal;
}