xxleyi / learning_list

聚集自己的学习笔记
10 stars 3 forks source link

Format Number with Comma #298

Open xxleyi opened 3 years ago

xxleyi commented 3 years ago

问题:把一个数字用逗号分隔,就是 12345.4444 变成 12,345.5555

解:关键点格式化正整数部分,所以需要先排除负数和小数带来的影响,然后专注于把一个正整数格式化成千位逗号分割。

function numberWithComma(n) {
  const [int, decimal] = n.split('.')
  const isPositive = int[0] === '-'
  const positiveInt = (isPositive ? int.slice(1) : int)
  const head = positiveInt.length % 3
  const rest = positiveInt.matchAll(new RegExp(`(?<=.{${head}}).{3}`, 'g'))
  const newInt = (isPositive ? '-' : '') + (head === 0 ? [...rest] : [positiveInt.slice(0, head), ...rest]).join(',')
  return decimal ? [newInt, decimal].join('.') : newInt
}
}