添加逗号作为千位分隔符(javascript) - 输出被删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13621769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding comma as thousands separator (javascript) - output being deleted instead
提问by Gideon
I am attempting to dynamically adjust a numerical value entered to include thousand separators
我正在尝试动态调整输入的数值以包含千位分隔符
Here is my code:
这是我的代码:
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '' + ',' + '');
}
return x1 + x2;
}
<input type="number" onkeyup="this.value=addCommas(this.value);" />
However when I enter numbers after the 4 one, the field is cleared.
但是,当我在 4 之后输入数字时,该字段被清除。
Any ideas where I am going wrong? If there is a jQuery solution I'm already using that on my site.
我哪里出错了?如果有一个 jQuery 解决方案,我已经在我的网站上使用了它。
采纳答案by Dillon Benson
Try
尝试
<input type="text" onkeyup="this.value=addCommas(this.value);" />
instead. Since the function is working with text not numbers.
反而。由于该函数使用的是文本而不是数字。
回答by phemt.latd
Try this regex:
试试这个正则表达式:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
回答by Isioma Nnodum
To add the thousands separator you could string split, reverse, and replace calls like this:
要添加千位分隔符,您可以字符串拆分、反转和替换这样的调用:
function addThousandsSeparator(input) {
var output = input
if (parseFloat(input)) {
input = new String(input); // so you can perform string operations
var parts = input.split("."); // remove the decimal part
parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, ",").split("").reverse().join("");
output = parts.join(".");
}
return output;
}
addThousandsSeparator("1234567890"); // returns 1,234,567,890
addThousandsSeparator("12345678.90"); // returns 12,345,678.90
回答by technosaurus
as Dillon mentioned, it needs to be a string (or you could use typeof(n) and stringify if not)
正如狄龙提到的,它需要是一个字符串(或者你可以使用 typeof(n) 和 stringify 如果不是)
function addCommas(n){
var s=n.split('.')[1];
(s) ? s="."+s : s="";
n=n.split('.')[0]
while(n.length>3){
s=","+n.substr(n.length-3,3)+s;
n=n.substr(0,n.length-3)
}
return n+s
}
回答by V.K.
In each case before formatting try to remove existing commas first, like there: Removing commas in 'live' input fields in jquery
在格式化之前的每种情况下,首先尝试删除现有的逗号,例如:Removingcommons in 'live' input fields in jquery
Example:
例子:
function addThousandsSeparator(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

