Add commas or spaces to group every three digits

前端 未结 9 1745
日久生厌
日久生厌 2020-11-27 15:50

I have a function to add commas to numbers:

function commafy( num ) {
  num.toString().replace( /\\B(?=(?:\\d{3})+)$/g, \",\" );
}

Unfortun

9条回答
  •  天命终不由人
    2020-11-27 16:30

    I have extended #RobG's answer a bit more and made a sample jsfiddle

    function formatNum(n, prec, currSign) {
        if(prec==null) prec=2;
      var n = ('' + parseFloat(n).toFixed(prec).toString()).split('.');
      var num = n[0];
      var dec = n[1];
      var r, s, t;
    
      if (num.length > 3) {
        s = num.length % 3;
    
        if (s) {
          t = num.substring(0,s);
          num = t + num.substring(s).replace(/(\d{3})/g, ",$1");
        } else {
          num = num.substring(s).replace(/(\d{3})/g, ",$1").substring(1);
        }
      }
        return (currSign == null ? "": currSign +" ") + num + (dec? '.' + dec : '');
    }
    alert(formatNum(123545.3434));
    alert(formatNum(123545.3434,2));
    alert(formatNum(123545.3434,2,'€'));
    

    and extended same way the #Ghostoy's answer

    function commafy( num, prec, currSign ) {
        if(prec==null) prec=2;
        var str = parseFloat(num).toFixed(prec).toString().split('.');
        if (str[0].length >= 5) {
            str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
        }
        if (str[1] && str[1].length >= 5) {
            str[1] = str[1].replace(/(\d{3})/g, '$1 ');
        }
        return (currSign == null ? "": currSign +" ") + str.join('.');
    }
    
    alert(commafy(123545.3434));
    

提交回复
热议问题