使用 Javascript 或 jQuery 将千位分隔符添加到总数中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2646385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a thousands separator to a total with Javascript or jQuery?
提问by Matt
I have a function that sums a column of data in an html table. It does so admirably only I would like to have it put the commas in there that are needed to separate the thousands. Initially, you'll note, there are commas in the numbers being added. So that the function will add them, they are removed. How do I add the commas back in there?
我有一个函数可以对 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>
回答by dave1010
The $(this).html().replace(',', '')
shouldn't actually modify the page. Are you sure the commas are being removed in the page?
该$(this).html().replace(',', '')
不该实际修改页面。您确定要删除页面中的逗号吗?
If it is, this addCommas functionshould do the trick.
如果是,这个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, '' + ',' + '');
}
return x1 + x2;
}
回答by Greg Valcourt
Use toLocaleString()
In your case do:
toLocaleString()
在你的情况下使用:
return "Total Pounds Entered : " + tot.toLocaleString();
回答by Ates Goral
This will add thousand separators while retaining the decimal part of a given number:
这将添加千位分隔符,同时保留给定数字的小数部分:
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
You could also probe for the locale's decimal separator with:
您还可以使用以下命令探测区域设置的十进制分隔符:
var sep = (0).toFixed(1)[1];
回答by Gusstavv Gil
I know this is an uber old post and has good answers, BUT if anyone is interested, there is a jQuery plugin which simplifies number formatting (thousands formatting, number of decimal places, custom thousands separator, etc) by making an include and a simple call. Has lots of features and documentation is enough. It's called jQuery Number.
我知道这是一个非常老的帖子并且有很好的答案,但是如果有人感兴趣,有一个 jQuery 插件可以通过创建一个包含和一个简单的来简化数字格式(千位格式、小数位数、自定义千位分隔符等)称呼。有很多功能和文档就足够了。它被称为jQuery Number。
You just include it:
你只需包括它:
<script type="text/javascript" src="jquery/jquery.number.min.js"></script>
And then use it:
然后使用它:
On an automatic formatting HTML input: $('input.number').number( true, 2 );
在自动格式化 HTML 输入上: $('input.number').number( true, 2 );
or
或者
On a JS call: $.number( 5020.2364, 2 ); // Outputs: 5,020.24
在 JS 调用中: $.number( 5020.2364, 2 ); // Outputs: 5,020.24
Hopefully this helps someone.
希望这有助于某人。
回答by Adam Marshall
I got somewhere with the following method:
我使用以下方法到达某个地方:
var value = 123456789.9876543 // i.e. some decimal number
var num2 = value.toString().split('.');
var thousands = num2[0].split('').reverse().join('').match(/.{1,3}/g).join(',');
var decimals = (num2[1]) ? '.'+num2[1] : '';
var answer = thousands.split('').reverse().join('')+decimals;
Using split-reverse-join is a sneaky way of working from the back of the string to the front, in groups of 3. There may be an easier way to do that, but it felt intuitive.
使用 split-reverse-join 是一种偷偷摸摸地从弦的后面到前面的工作方式,以 3 为一组。可能有一种更简单的方法来做到这一点,但它感觉很直观。
回答by stefansundin
This is how I do it:
这就是我的做法:
// 2056776401.50 = 2,056,776,401.50
function humanizeNumber(n) {
n = n.toString()
while (true) {
var n2 = n.replace(/(\d)(\d{3})($|,|\.)/g, ',')
if (n == n2) break
n = n2
}
return n
}
Or, in CoffeeScript:
或者,在 CoffeeScript 中:
# 2056776401.50 = 2,056,776,401.50
humanizeNumber = (n) ->
n = n.toString()
while true
n2 = n.replace /(\d)(\d{3})($|,|\.)/g, ','
if n == n2 then break else n = n2
n
回答by dkellner
Consider this:
考虑一下:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ," " )
.replace(/(\d+)(\d{3})$/ ," " )
.replace(/(\d+)(\d{3})(\d{3})\./ ," .")
.replace(/(\d+)(\d{3})\./ ," ." )
;
}
It's a quick solution for anything under 999.999.999, which is usually enough. I know the drawbacks and I'm not saying this is the ultimate weapon - but it's just as fast as the others above and I find this one more readable. If you don't need decimals you can simplify it even more:
对于低于 999.999.999 的任何内容,这是一个快速解决方案,这通常就足够了。我知道缺点,我并不是说这是终极武器——但它和上面的其他武器一样快,我发现这个更易读。如果您不需要小数,您可以进一步简化它:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ," ")
.replace(/(\d+)(\d{3})$/ ," " )
;
}
Isn't it handy.
是不是很方便。
回答by Khalid Habib
best and simple way to format the number is to use java-script function
格式化数字的最好和最简单的方法是使用 java-script 函数
var numberToformat = 1000000000
//add locality here, eg: if you need English currency add 'en' and if you need Danish currency format then use 'da-DA'.
var locality = 'en-EN';
numberToformat = numberToformat.toLocaleString(locality , {
minimumFractionDigits: 4 })
document.write(numberToformat);
for more information click documentation page
有关更多信息,请单击文档页面
回答by chad steele
Seems like this is ought to be the approved answer...
似乎这应该是批准的答案......
Intl.NumberFormat('en-US').format(count)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
回答by Jay Nguyê?n
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
Use:
用:
numberWithCommas(200000);
==> 200,000
==> 200,000