Add commas or spaces to group every three digits

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

    Here you go edited after reading your comments.

    function commafy( arg ) {
       arg += '';                                         // stringify
       var num = arg.split('.');                          // incase decimals
       if (typeof num[0] !== 'undefined'){
          var int = num[0];                               // integer part
          if (int.length > 4){
             int     = int.split('').reverse().join('');  // reverse
             int     = int.replace(/(\d{3})/g, "$1,");    // add commas
             int     = int.split('').reverse().join('');  // unreverse
          }
       }
       if (typeof num[1] !== 'undefined'){
          var dec = num[1];                               // float part
          if (dec.length > 4){
             dec     = dec.replace(/(\d{3})/g, "$1 ");    // add spaces
          }
       }
    
       return (typeof num[0] !== 'undefined'?int:'') 
            + (typeof num[1] !== 'undefined'?'.'+dec:'');
    }
    

提交回复
热议问题