Skip to content

金额千分位

84 字小于 1 分钟

js

2024-12-28

通过substring截取字符串实现千分位

function toThousand(money) {
  money= money.toString()
  let result = ''
  while (money.length > 3) {
    result = ',' + money.substring(money.length - 3) + result
    money = money.substring(0, money.length - 3)
  }
  result = money + result
  return result
}

方法二

通过正则实现

const toThousand = (money) => {
  return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')  
}

toThousand('123456789') // '123,456,789'