I'm using the following jQuery plug-in to automatically add commas to a number. The problem is, when a decimal amount (like $1,000.00) is entered, it's changing it to $1,000,.00.
我正在使用以下jQuery插件自动为数字添加逗号。问题是,当输入十进制数量(如$ 1,000.00)时,它会将其更改为$ 1,000,.00。
How can the regex be updated to ignore the decimal point and any characters after it?
如何更新正则表达式以忽略小数点和后面的任何字符?
String.prototype.commas = function() {
return this.replace(/(.)(?=(.{3})+$)/g,"$1,");
};
$.fn.insertCommas = function () {
return this.each(function () {
var $this = $(this);
$this.val($this.val().replace(/(,| )/g,'').commas());
});
};
3 个解决方案
#1
1
seems like a simple fix. Just change the .{3}
(any three characters) to [^.]{3}
(any non-period three characters)
似乎是一个简单的修复。只需将。{3}(任意三个字符)更改为[^。] {3}(任何非句点三个字符)
String.prototype.commas = function() {
return this.replace(/(.)(?=([^.]{3})+$)/g,"$1,");
};
EDIT:
编辑:
or better yet:
或者更好的是:
String.prototype.commas = function() {
return this.replace(/(\d)(?=([^.]{3})+($|[.]))/g,"$1,");
};
#2
1
Here is an excellent answer already on *: How can I format numbers as money in JavaScript?
这是*上的一个很好的答案:如何在JavaScript中将数字格式化为金钱?
Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Here is a demo: http://jsfiddle.net/H4KLD/
这是一个演示:http://jsfiddle.net/H4KLD/
#3
1
This should work as long as there are no more than 3 digits after the .
:
只要在。之后不超过3位数,这应该有效。
replace(/(\d)(?=(?:\d{3})+(?:$|\.))/g, "$1,");
#1
1
seems like a simple fix. Just change the .{3}
(any three characters) to [^.]{3}
(any non-period three characters)
似乎是一个简单的修复。只需将。{3}(任意三个字符)更改为[^。] {3}(任何非句点三个字符)
String.prototype.commas = function() {
return this.replace(/(.)(?=([^.]{3})+$)/g,"$1,");
};
EDIT:
编辑:
or better yet:
或者更好的是:
String.prototype.commas = function() {
return this.replace(/(\d)(?=([^.]{3})+($|[.]))/g,"$1,");
};
#2
1
Here is an excellent answer already on *: How can I format numbers as money in JavaScript?
这是*上的一个很好的答案:如何在JavaScript中将数字格式化为金钱?
Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Here is a demo: http://jsfiddle.net/H4KLD/
这是一个演示:http://jsfiddle.net/H4KLD/
#3
1
This should work as long as there are no more than 3 digits after the .
:
只要在。之后不超过3位数,这应该有效。
replace(/(\d)(?=(?:\d{3})+(?:$|\.))/g, "$1,");