Skip to content

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

Open

Description

@wingmeng

题目:

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

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
  ));
}

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions