• js实现数字每三位加逗号


    需求:

    一个数字,比如 1234,23456.23 实现每三位加逗号

    改成如下形式:

    1234 => 1,234

    23456.23 => 23,456.23

    方法一

    function formateNum (num) {
        let str = String(num);
        let strStart = str, strEnd = ''
        if (str.indexOf('.') != -1) {
          strStart = str.split('.')[0];
          strEnd = str.split('.')[1];
        }
        let len = strStart.length;
        let count = 0;
        let newStr = ''
        for (let i = len - 1; i >= 0; i--) {
          if (count % 3 == 0 && count != 0) {
            newStr = strStart[i] + ',' + newStr
          } else {
            newStr = strStart[i] + newStr;
          }
          count++;
        }
        if (strEnd) {
          newStr = newStr + '.' + strEnd;
        }
        return newStr;
      }
      let num = 129874.78;
      console.log(formateNum(num)); // 129,874.78
      let num1 = 33245;
      console.log(formateNum(num1)); // 33,245

    方法二:

    /**
     * 12345 => $12,345.00
     *
     * @param  {[type]} value    [description]
     * @param  {[type]} currency [description]
     * @return {[type]}          [description]
     */
    function currency(value, currency) {
    
      value = parseFloat(value)
    
      if (!isFinite(value) || (!value && value !== 0)) {
    
        return ''
      }
    
      currency = currency !== null ? currency : '$'
      let stringified = Math.abs(value).toFixed(2)
      let _int = stringified.slice(0, -3)
      let i = _int.length % 3
      let head = i > 0
        ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
        : ''
      let _float = stringified.slice(-3)
      let sign = value < 0 ? '-' : ''
    
      return currency + sign + head +
        _int.slice(i).replace(digitsRE, '$1,') +
        _float
    }
  • 相关阅读:
    六、Redis主从复制 
    五、AOF持久化
    四、RDB持久化
    三、数据类型
    二、redis的配置文件介绍
    第八章、堆
    九、补充
    八、Filter
    七、监听器和国际化
    六、JDBC
  • 原文地址:https://www.cnblogs.com/aimee2004/p/8669206.html
Copyright © 2020-2023  润新知