#18 数字添加逗号


  • 0

    function commafy (num) {
        if (typeof num === 'number') {
            var arr = num.toString().split('.'),
                intStr = Math.abs(arr[0]).toString(), // 绝对值的整数字符串
                decimals = arr[1] ? `.${arr[1]}` : '', // 小数字符串
                intArr = intStr.split(''), 
                minus = num < 0 ? '-' : ''; // 符号位字符串
    
            if (intStr == 0) {
                return num.toString()
            } 
            
            for (var i = 0, len = intArr.length; i < len; i++) {
                if (i % 3 === 0 && i !== 0) {
                    intArr.splice(len - i, 0, ',');
                }
            }
            
            return minus + intArr.join('') + decimals; // 符号位 + 整数字符串 + 小数字符串
        }
    }
    

    求优化,和最优方案-。-除了正则那个


  • 2

    还是正则方便

    function commafy (num) {
      let arr=num.toString().split('.')
      var integer=arr[0].replace(/(?!\b)(?=(\d{3})+$)/g,',')
      if(arr[1]){
        return integer+'.'+arr[1]
      }else return integer
    }
    

  • 2

    0_1498795275807_TIM截图20170630115656.png
    写的有点乱


  • 0

    function commafy (num) {
      const arr = num.toString().split('.');
      let result = arr[0].split('').reverse().reduce((pre,next,index) => {
        if(index%3 !== 0 || next === '-'){
          return pre = ''.concat(next,pre)
        }else{
          return pre = ''.concat(next,',',pre)
        }
      })
      let right = arr[1]
      return right ? ''.concat(result,'.',right) : ''.concat(result)
    }
    
    

  • 0

    function commafy (num) {
    /* TODO */
    if(num<0){
    return num+'';
    }else{
    return num.toLocaleString();
    }
    }

    为啥不对啊 返回的是字符串啊


  • 0

    le = function(num){
    return Number(num).toLocaleString();
    }
    console.log(le(12000000.11));


  • 0

    function commafy (num) {
     let arr = num.toString().split('.');
     return (arr[0] == '-0' ? '-0' :Number(arr[0])).toLocaleString().concat(arr[1]?'.'+arr[1]:'');
    }

  • 0

    function commafy(num) {
      var arr = num.toString().split(".");
      return arr[0].replace(/\B(?=(?:\d{3})+\b)/g, ",") + (arr[1] ? "."+arr[1] : "");
    }
    

  • 0

    每天上班到这个时候感觉头都晕了,胡乱写成了这样,明天再重新写一下吧

    function commafy(num) {
    
       var str = "";
       if (num < 0) {
           str = "-";
           num = num * -1;
       }
    
       //判断整数部分位数是否大于3位
       if (num.toString().split(".")[0].length <= 3) {
           return str + num.toString();
       }
    
       var numInt = num.toString().split(".")[0],
           strDecimal = "";
    
       //是否有小数点
       if (num.toString().indexOf(".") !== -1) {
           strDecimal = "." + num.toString().split(".")[1];
       }
    
       var strNum = numInt.toString(),
           arrNum = strNum.split(""),
           remainder = arrNum.length % 3,
           commaNum = parseInt(strNum.length / 3 - 1),
           index = 0;
    
       //整数部分位数是否是3的整数倍
       if (remainder !== 0) {
           commaNum++;
           index = remainder;
       } else {
           index = 3;
       }
    
       //循环插入逗号
       var n = 0;
       while (n < commaNum) {
           arrNum.splice(index, 0, ",");
           index = index + 3;
           index++;
           n++;
       }
       return str + arrNum.join("") + strDecimal;
    }

  • 0

    function commafy(num) {
      let numString = num.toString();
      let wholePart = numString.match(/\d+/g)[0];
      let smallPart = numString.match(/\d+/g)[1];
      let wholePartNum = parseInt(wholePart);
      let res = '';
      if (num < 0) {
        res += '-';
      }
      res += wholePartNum.toLocaleString();
      if (smallPart) {
        res += '.' + smallPart;
      }
      return res;
    }
    

    分享一下哈


  • 0

    function commafy(num) {
        const reg = /(\-?\d{1,3})(?=(\d{3})+$)/g
        const numPre = num.toString().split('.')[0]
        const numNext = num.toString().split('.')[1]
        const numNextStr = numNext ? `.${numNext}` : ''
        return numPre.toString().replace(reg, '$&,') + numNextStr
    }
    

  • 0

    function commafy (num) {
    return (num).toLocaleString(undefined, { maximumFractionDigits: 12 })
    }
    // maximumFractionDigits :保留浮点数位数

    这一行就够了啊·~·~已经通过


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待