在做一个智利的项目的时候,有个算buget的页面,需要显示货币时数字之间每3位用逗号分隔,而且计算都是在客户端进行,所以就用javascript实现。
代码如下,包含了加逗号和移除逗号
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, '$1' + ',' + '$2');
}
return x1 + x2;
}
function remCommas(nStr)
{
return nStr.replace(/\./g , '').replace('%','').replace(' ','').replace(',','.');
}