我看到了一个优美的脚本,可以给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;
}
用法:
thousandSeparator(5000000.125, '\,') //"5,000,000.125"
然而,我对while循环有些困惑。
我考虑将正则表达式更改为:'(-?[0-9]+)([0-9]{3})*'
星号...
但是,现在我该如何应用替换语句呢?
现在,我会有$1
和$2..$n
我该如何增强替换函数呢?
p.s. 代码取自这里 http://www.grumelo.com/2009/04/06/thousand-separator-in-javascript/
5000000.125678
上失败了 ->5,000,000.125,678
- zerkms(-?[0-9]+)([0-9]{3})(?=\.)
,但它没有起作用...我的意思是,只替换右侧有小数点的数字。 - Royi Namir