jQuery函数用逗号和小数格式化数字

我正在使用以下函数来格式化数字作为用户类型。 它将每3个数字插入一个逗号。 例: 45696.36变为45,696.36

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

这是我的function:

 $.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。 谢谢!

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

 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 

我使用accounting.js lib:

 accounting.format(1136.6696, 4) // 1,136.6696