Add commas or spaces to group every three digits

前端 未结 9 1705
日久生厌
日久生厌 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

    If you are happy with the integer part (I haven't looked at it closly), then:

    function formatDecimal(n) {
      n = n.split('.');
      return commafy(n[0]) + '.' + n[1];
    }
    

    Of course you may want to do some testing of n first to make sure it's ok, but that's the logic of it.

    Edit

    Ooops! missed the bit about spaces! You can use the same regular exprssion as commafy except with spaces instead of commas, then reverse the result.

    Here's a function based on vol7ron's and not using reverse:

    function formatNum(n) {
      var n = ('' + n).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);
        }
      }
    
      if (dec && dec.length > 3) {
        dec = dec.replace(/(\d{3})/g, "$1 ");
      }
    
      return num + (dec? '.' + dec : '');
    }
    

提交回复
热议问题