【问题标题】:Add thousands separator to auto sum将千位分隔符添加到自动总和
【发布时间】:2011-09-24 01:05:06
【问题描述】:
我希望从下面的脚本计算的总和显示两位小数,千位用逗号分隔。在这个阶段它只显示两位小数。我是编程新手,尝试了各种技术,但无法解决问题。到目前为止,在我的 JS 代码下方:
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2).replace(',', ''));
}
【问题讨论】:
标签:
javascript
jquery
number-formatting
【解决方案1】:
sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,')
解释:
在字符串的开头找到 1 到 3 位数字,后跟至少三位数字,后跟小数点或数字末尾(因此相同的正则表达式适用于整数以及有 2 位小数的数字。)
【解决方案2】:
你需要使用这样的东西:
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 calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(addCommas(sum.toFixed(2)));
}
【解决方案3】:
function DigitsFormat(str) {
return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}
【解决方案4】:
这是一种在整数部分添加千位分隔符的非正则表达式方式:
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}