我试图用逗号作为千位分隔符在JavaScript中打印一个整数.例如,我想将数字1234567显示为"1,234,567".我该怎么做呢?
我是这样做的:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
Run Code Online (Sandbox Code Playgroud)
有更简单或更优雅的方式吗?如果它也适用于浮点数会很好,但这不是必需的.它不需要特定于语言环境来决定句点和逗号.
我看到了这个漂亮的脚本,为js数字添加了数千个分隔符:
function thousandSeparator(n, sep)
{
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue = n + '';
if(sep === undefined)
{
sep = ',';
}
while(sRegExp.test(sValue))
{
sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
}
return sValue;
}
Run Code Online (Sandbox Code Playgroud)
用法:
thousandSeparator(5000000.125, '\,') //"5,000,000.125"
Run Code Online (Sandbox Code Playgroud)
但是我在接受while循环时遇到了麻烦。
我正在考虑将正则表达式更改为:'(-?[0-9]+)([0-9]{3})*' 星号 ...
但是现在,我该如何应用replace语句?
现在我将$1和$2..$n
如何增强替换功能?
ps的代码是从这里http://www.grumelo.com/2009/04/06/thousand-separator-in-javascript/