Add commas or spaces to group every three digits

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

    Just split into two parts with '.' and format them individually.

    function commafy( num ) {
        var str = num.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 str.join('.');
    }
    

提交回复
热议问题