输出数字,3 位数字后带逗号

Output numbers with comma after 3 digits

本文关键字:数字 输出      更新时间:2023-09-26

我使用了这个jQuery代码

jQuery.fn.digits = function(){ 
    return this.each(function(){ 
        jQuery(this).text( $(this).text().replace(/('d)(?=('d'd'd)+(?!'d))/g, "$1,") ); 
    })
}

对于数字 150000我希望它能放出150,000

但它输出这个:150,000.00

我不想要这些额外的.00

我发现for循环比正则表达式更容易理解。

function addCommas(num) {
    var characters = parseInt(num, 10).toString();
    var output = '';
    for (var offset = characters.length; offset > 0; offset -= 3) {
        output = characters.slice(Math.max(offset - 3, 0), offset) + (output ? ',' + output : '');
    }
    return output;
}

您可以使用 JQuery Number 格式化程序插件,因此您不必处理这样的正则表达式来格式化您的数字:

Jquery Number 格式化程序

另一种解决方法是只修剪最后 3 个字符

$(this).text().replace(/('d)(?=('d'd'd)+(?!'d))/g, "$1,").slice(0,-3)

在正则表达式之前尝试 Math.round,然后在之后尝试子字符串 - 这是未经测试的

var newnumber = Math.round(parseInt($(this).text());
var withcommas = newnumber.replace(/('d)(?=('d'd'd)+(?!'d))/g, "$1,");
$(this).text(withcommas.substring(0, s.indexOf('.')));