封装一个保留千分位的函数,并且保留两位小数

const thousandsFilter = (data) => {
  if (!isNaN(data)) {
    if (data > 999 || data < -999) {
      let dataStr = data.toString() + '.00'
      let integer
      let newdata = ''
      let flg = ','
      integer = dataStr
      for (let i = integer.length; i > 0; i -= 3) {
        let tmp = integer.substring(i - 3, i)
        if (i - 3 <= 0) {
          newdata = tmp + newdata
        } else newdata = flg + tmp + newdata
      }
      return newdata  // 传入数字,返回的是字符串
    } else {
      return data
    }
  } else {
    return data
  }
}

封装一个保留千分位的函数,不保留小数位

const thousandsFilter = (data) => {
  if (!isNaN(data)) {
    if (data > 999 || data < -999) {
      let dataStr = data.toString()
      let integer, decimals
      let newdata = ''
      let flg = ','
      if (dataStr.indexOf('.') !== -1) {
        integer = dataStr.split('.')[0]
        decimals = dataStr.split('.')[1]
        for (let i = integer.length; i > 0; i -= 3) {
          var tmp = integer.substring(i - 3, i)
          if (i - 3 <= 0) {
            newdata = tmp + newdata
          } else newdata = flg + tmp + newdata
        }
        newdata = newdata + '.' + decimals
      } else {
        integer = dataStr
        for (let i = integer.length; i > 0; i -= 3) {
          let tmp = integer.substring(i - 3, i)
          if (i - 3 <= 0) {
            newdata = tmp + newdata
          } else newdata = flg + tmp + newdata
        }
      }
      return newdata
    } else {
      return data
    }
  } else {
    return data
  }
}
01-09 16:21