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

第 27 期(ECMAScript-正则表达式):金额数值格式化 #30

Open
wingmeng opened this issue Jun 5, 2019 · 0 comments
Open

第 27 期(ECMAScript-正则表达式):金额数值格式化 #30

wingmeng opened this issue Jun 5, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 5, 2019

题目:

请实现一个按千分位格式化金额数值的功能

function formatMoney(num) {
  // 你的代码
}

测试用例:

formatMoney(100);  // 100.00
formatMoney(1000);  // 1,000.00
formatMoney(1000.56);  // 1,000.56
formatMoney(1000000000.25);  // 1,000,000,000.25

参考答案:

function formatMoney(num) {
  // 字符串捕获(零宽度正预测先行断言)
  let regex = /\d{1,3}(?=(\d{3})+$)/g;

  // 将字符串拆分成“符号”(如有)、“整数位”和“小数位”三部分
  return String(num).replace(/^(-|\+?)(\d+)((\.\d+)?)$/, (s, s1, s2, s3) => (
    // $&表示 replace() 函数第一个正则表达式参数所匹配的内容
    s1 + s2.replace(regex, '$&,') + s3
  ));
}

相关资料:正则表达式零宽断言

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

No branches or pull requests

1 participant