我有一个函数来汇总html表中的一列数据.它确实令人钦佩,我只想把它放在那里,需要将数千个分开.最初,您会注意到,添加的数字中有逗号.因此该函数将添加它们,它们将被删除.如何在那里添加逗号?
<script type="text/javascript">
function sumOfColumns(tableID, columnIndex, hasHeader) {
var tot = 0;
$("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
.children("td:nth-child(" + columnIndex + ")")
.each(function() {
tot += parseInt($(this).html().replace(',', ''));
});
return "Total Pounds Entered : " + tot;
}
</script>
Run Code Online (Sandbox Code Playgroud)
dav*_*010 81
该$(this).html().replace(',', '')不该实际修改页面.你确定在页面中删除了逗号吗?
如果是,这个addCommas函数应该可以解决问题.
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Run Code Online (Sandbox Code Playgroud)
Gre*_*urt 20
使用toLocaleString()
在你的情况下做:
return "Total Pounds Entered : " + tot.toLocaleString();
Run Code Online (Sandbox Code Playgroud)
Ate*_*ral 18
这将添加千位分隔符,同时保留给定数字的小数部分:
function format(n, sep, decimals) {
sep = sep || "."; // Default to period as decimal separator
decimals = decimals || 2; // Default to 2 decimals
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
format(4567354.677623); // 4,567,354.68
Run Code Online (Sandbox Code Playgroud)
您还可以使用以下方法探测区域设置的小数分隔符:
var sep = (0).toFixed(1)[1];
Run Code Online (Sandbox Code Playgroud)
似乎这应该是批准的答案......
Intl.NumberFormat('en-US').format(count)
Run Code Online (Sandbox Code Playgroud)
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
小智 5
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
Run Code Online (Sandbox Code Playgroud)
用:
numberWithCommas(200000);
Run Code Online (Sandbox Code Playgroud)
==> 200,000
| 归档时间: |
|
| 查看次数: |
86809 次 |
| 最近记录: |