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

将 153812.7 转化为 153,812.7 #244

Open
lgwebdream opened this issue Jul 6, 2020 · 3 comments
Open

将 153812.7 转化为 153,812.7 #244

lgwebdream opened this issue Jul 6, 2020 · 3 comments
Labels
JavaScript teach_tag 编程题 teach_tag

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 编程题 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@GolderBrother
Copy link

function parseMoney(num) {
    let [interger, decimal ] = String.prototype.split.call(num, '.');
    interger = interger.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
    decimal = decimal ? `.${decimal}` : '';
    return interger + decimal;
}
console.log(parseMoney(153812.7));

@gaohan1994
Copy link

const splitNumber = num => {
  const base = `${Number(num)}`;
  const [integer, decimal] = base.split(".");

  let result = "";
  let currentNumber = "";

  for (let index = integer.length - 1; index >= 0; index--) {
    const char = integer[index];

    if (char && currentNumber.length < 3) {
      console.log("currentNumber length < 3 should add to current number");
      currentNumber = `${char}${currentNumber}`;
    }

    if (currentNumber.length === 3) {
      result = `${index !== 0 ? "," : ""}${currentNumber}${result}`;
      currentNumber = "";
      console.log("currentNumber = 3 should add to result, after added result: ", result);
    }
  }

  if (decimal) {
    result = `${result}.${decimal}`;
  }

  return result;
};
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 编程题 teach_tag
Projects
None yet
Development

No branches or pull requests

3 participants