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

封装一个保留千分位的函数,并且保留两位小数(输入:123456,输出:123,456.00)

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) {
        dataStr = Number(dataStr).toFixed(2)
        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 + '.00'
          } else newdata = flg + tmp + newdata
        }
      }
      return newdata // 传入数字,返回字符串
    } else {
      return data
    }
  } else {
    return data
  }
}

封装一个保留千分位的函数,不保留小数位(输入:123456,输出:123,456)

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
  }
}

  

posted @ 2019-10-31 15:49  小提莫~  阅读(839)  评论(0编辑  收藏  举报