Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

千分位分割数字 #63

Open
nmsn opened this issue Nov 17, 2022 · 0 comments
Open

千分位分割数字 #63

nmsn opened this issue Nov 17, 2022 · 0 comments

Comments

@nmsn
Copy link
Owner

nmsn commented Nov 17, 2022

function format(num) {
  num = num.toString();
  const [integer, decimal] = num.split(".");

  if (integer.length < 3) {
    return num;
  }
  
  const remainder = integer.length % 3;

  let integerStr = "";
  const decimalStr = decimal ? `.${decimal}` : "";

  if (remainder > 0) {
    // 不是正数倍
    integerStr = `${integer.slice(0, remainder)},${insert(
      integer.slice(remainder)
    )}`;
  } else {
    // 能够整除
    integerStr = insert(integer);
  }

  return `${integerStr}${decimalStr}`;
}

// 工具函数,给字符串插入 ','
function insert(str) {
  return str.match(/\d{3}/g).join(",");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant