Skip to content

千分位分割

🕒 Published at:

无负数和无小数版

js
let str = '1000000000'
let reg = /(?=(\B)(\d{3})+$)/g
console.log(str.replace(reg, ',') === '1,000,000,000')

支持负数和小数版

js
function format(str) {
  let string = ''
  let minus = ''
  let decimal = ''
  if (str.indexOf('-') === 0) {
    string = str.slice(1)
    minus = '-'
    if (str.includes('.')) {
      ;[string, decimal] = string.split('.')
    }
  } else {
    if (str.includes('.')) {
      ;[string, decimal] = str.split('.')
    } else {
      string = str
    }
  }
  const reg = /(?=(\B)(\d{3})+$)/g
  if (decimal) {
    return minus + string.replace(reg, ',') + '.' + decimal
  } else {
    return minus + string.replace(reg, ',')
  }
}

console.log(format('1000'))
console.log(format('1000000000'))
console.log(format('1000000000.999'))
console.log(format('-1000000000'))
console.log(format('-1000000000.999'))