[Javascript]-數字加上千分位並顯示小數點

數字加上千分位並顯示小數點

傳入(數字,要顯示幾位小數)

<script>
const thousandsFilter = (data,tofixed) => {
  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(tofixed)
        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
  }
}





a=thousandsFilter(12345678.987,2)
console.log(a) //12,345,678.99
</script>

 

 

 

YiruAtStudio - 關於我 - 意如