#18 数字添加逗号


  • 0
    administrators

    完成函数 commafy,它接受一个数字作为参数,返回一个字符串,可以把整数部分从右到左每三位数添加一个逗号,如:12000000.11 转化为 12,000,000.11。


  • 0

    I got stuck at a test case, where it inputs 4004, I believe it should output 4,004, but it told me its wrong answer and the correct should be 4004?


  • 0
    administrators

    也许是测试用例有问题,我看看。


  • 0
    administrators

    @inizio Yes, there was an issue about its test case. I updated it. It's my apology. You can submit your solution again, should be all right.


  • 0

    Thanks you!


  • 0
    administrators

    @inizio Also thanks your feedback :)


  • 0

    @胡子大哈 感觉这题应该考得是 currency 的写法吧 不然其实非常奇怪


  • 0

    0_1494862774488_屏幕快照 2017-05-15 下午11.39.18.png

    请问运行信息的错误是。。?


  • 0
    administrators

    @Saku 要返回字符串


  • 0

    @胡子大哈 哦明白


  • 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; // 符号位 + 整数字符串 + 小数字符串
        }
    }
    

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


  • 0

    还是正则方便

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

    分享一下哈


登录后回复
 

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