15

我正在使用以下函数在用户键入时格式化数字。它将每 3 个数字插入一个逗号。例如:45696.36变成45,696.36

但是,我遇到了一个问题。如果小数点后的数字超过 3 位,则开始添加逗号。例如:1136.6696变成1,136.6,696

这是我的功能:

$.fn.digits = function(){
  return this.each(function() {
    $(this).val( $(this).val().replace(/[^0-9.-]/g, '') );
    $(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
  }) 
}

我该如何解决这个问题,使其停止在小数点后放置逗号?我正在使用 jQuery 1.8。谢谢!

4

2 回答 2

54

您可以通过在 ' .' 字符处拆分字符串然后仅在第一部分执行逗号转换来完成此操作,如下所示:

function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n= yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //Combines the two sections
    return n.join(".");
}

ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696

例子

于 2012-12-28T19:58:18.670 回答
2

我使用accounting.js lib:

accounting.format(1136.6696, 4) // 1,136.6696
于 2016-09-30T21:26:10.653 回答