AymaxLi / AymaxLi.github.io

:point_right: my blog,show in issues ~

Home Page:https://github.com/AymaxLi/AymaxLi.github.io/issues

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

用正则格式化金额

AymaxLi opened this issue · comments

commented

Background

前端处理页面经常会有格式化金额的需求,常用的格式为 12,345,678.12 ,即整数部分每三位用逗号隔开,保留两位小数。

Resolution

正则

捕获逗号前的数字,不捕获逗号后的位置,把逗号前捕获的数字替换成 $1,

function formatAmount(input) {
  const amount = Number(input)

  // 判断输入是否合法
  if (Number.isNaN(amount) || input === '') return '输入金额不合法!'

  // 先保留两位小数,再插入逗号
  return amount.toFixed(2).replace(/(\d{1,3})(?=(?:\d{3})+\.)/g,'$1,')
}

['', '12', '12345', '12345678.123', 'abc'].forEach(el => {
  console.log(formatAmount(el))
})