通过JavaScript将传递的数字加上千分位(‘,’)

752 阅读2分钟

要做的是封装一个函数,当通过函数传递一个number,它会输出一个字符串千分位会用(,)隔开.如下例

//函数传入1234567
//传出字符串的1,234,567

一,遍历方法

    // 一,遍历方法
    function qianFenWei(num) {
      // 将数字转成字符串
      num += ''
      // 声明输出的结果变量
      let result = ''
      // split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
      num = num.split('')
      num.forEach((item, index) => {
        // 遍历时,后遍历的数需放入先遍历的数前面
        result += item
        // 每隔3位加一个逗号
        if (index % 3 === 2 && index !== num.length - 1) {
          result += ','
        }
      })

      return result
    }
    console.log(qianFenWei(1234567))//浏览器控制台打印1,234,567

二,倒序遍历方法

    function qianFenWei(num) {
      // 将数字转成字符串
      num += ''
      // 声明输出的结果变量
      let result = ''
      // 倒序遍历
      // reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
      num = num.split('').reverse()
      num.forEach((item, index) => {
        // 遍历时,后遍历的数需放入先遍历的数前面
        result = item + result
        // 每隔3位加一个逗号
        if (index % 3 === 2 && index !== num.length - 1) {
          result = ',' + result
        }
      })

      return result
    }
    console.log(qianFenWei(1234567))//浏览器控制台打印1,234,567

三,判断长度,分开处理,最后用(,)拼接

 function qianFenWei(num) {
      // 0. 将数字转成字符
      num += ''
      const len = num.length
      // 获取剩余长度
      const remainderLen = len % 3
      // 取出剩余字符串
      const result = remainderLen ? [num.substring(0, remainderLen)] : []
      // 对其余长度是3的倍数的字符做遍历
      for (let i = remainderLen; i < len; i += 3) {
        result.push(num.substring(i, i + 3));
      }
      // join用,拼接
      return result.join(',');
    }
    console.log(qianFenWei(1234567))

四,正则表达式

 function qianFenWei(num) {
      // 将number转为字符串
      num += ''
      const result = num.replace(/(?<!^)(?=(\d{3})+$)/g, ',')
      return result
    }
    console.log(qianFenWei(1234567))