使用Javascript或jQuery为总计添加千位分隔符?

时间:2022-10-31 22:52:17

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>

10 个解决方案

#1


68  

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 function should 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, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

#2


16  

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];

#3


12  

Use toLocaleString()
In your case do:

使用toLocaleString()在你的情况下做:

return "Total Pounds Entered : " + tot.toLocaleString(); 

#4


2  

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, '$1,$2$3')
    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, '$1,$2$3'
    if n == n2 then break else n = n2
  n

#5


2  

Consider this:

考虑一下:

function group1k(s) {
    return (""+s)
        .replace(/(\d+)(\d{3})(\d{3})$/  ,"$1 $2 $3" )
        .replace(/(\d+)(\d{3})$/         ,"$1 $2"    )
        .replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
        .replace(/(\d+)(\d{3})\./        ,"$1 $2."   )
    ;
}

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})$/ ,"$1 $2 $3")
        .replace(/(\d+)(\d{3})$/        ,"$1 $2"   )
    ;
}

Isn't it handy.

不方便。

#6


2  

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); //输出:5,020.24

Hopefully this helps someone.

希望这有助于某人。

#7


0  

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个为一组。可能有一种更简单的方法,但它感觉直观。

#8


0  

a recursive solution:

递归解决方案:

function thousands(amount) {
  if( /\d{3}\d+/.test(amount) ) {
    return thousands(amount.replace(/(\d{3}?)(,|$)/, ',$&'));
  }
  return amount;
}

another split solution:

另一个解决方案:

function thousands (amount) {
  return amount.split('').reverse().join('').replace(/\d{3}/g, '$&,').split('').reverse().join('');
}

#9


0  

Below is the working Example:

以下是工作示例:

 $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));  

This line is sufficient, it works for me. Check the complete code below. Let me know if it works fine for you too.

这条线就足够了,对我来说很有用。检查下面的完整代码。让我知道它是否适合你。

$(".action.showcart").on('click', function() {
    var miniCartTotal = $("#estimated-subtotal .price").html();
    var miniCartTotalString = miniCartTotal.replace(/\$/g, '');
    var miniCartTotalString = miniCartTotalString.replace(/,/g, ''); 
    var configValue = 5; 

    miniCartTotal = parseFloat(miniCartTotalString) + configValue;
    console.log("updated value " + miniCartTotal);

    $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
});

#10


0  

best and simple way to format the number is to use java-script function

格式化数字的最佳和简单方法是使用java脚本函数

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

有关更多信息,请单击文档页面

#1


68  

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 function should 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, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

#2


16  

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];

#3


12  

Use toLocaleString()
In your case do:

使用toLocaleString()在你的情况下做:

return "Total Pounds Entered : " + tot.toLocaleString(); 

#4


2  

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, '$1,$2$3')
    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, '$1,$2$3'
    if n == n2 then break else n = n2
  n

#5


2  

Consider this:

考虑一下:

function group1k(s) {
    return (""+s)
        .replace(/(\d+)(\d{3})(\d{3})$/  ,"$1 $2 $3" )
        .replace(/(\d+)(\d{3})$/         ,"$1 $2"    )
        .replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
        .replace(/(\d+)(\d{3})\./        ,"$1 $2."   )
    ;
}

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})$/ ,"$1 $2 $3")
        .replace(/(\d+)(\d{3})$/        ,"$1 $2"   )
    ;
}

Isn't it handy.

不方便。

#6


2  

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); //输出:5,020.24

Hopefully this helps someone.

希望这有助于某人。

#7


0  

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个为一组。可能有一种更简单的方法,但它感觉直观。

#8


0  

a recursive solution:

递归解决方案:

function thousands(amount) {
  if( /\d{3}\d+/.test(amount) ) {
    return thousands(amount.replace(/(\d{3}?)(,|$)/, ',$&'));
  }
  return amount;
}

another split solution:

另一个解决方案:

function thousands (amount) {
  return amount.split('').reverse().join('').replace(/\d{3}/g, '$&,').split('').reverse().join('');
}

#9


0  

Below is the working Example:

以下是工作示例:

 $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));  

This line is sufficient, it works for me. Check the complete code below. Let me know if it works fine for you too.

这条线就足够了,对我来说很有用。检查下面的完整代码。让我知道它是否适合你。

$(".action.showcart").on('click', function() {
    var miniCartTotal = $("#estimated-subtotal .price").html();
    var miniCartTotalString = miniCartTotal.replace(/\$/g, '');
    var miniCartTotalString = miniCartTotalString.replace(/,/g, ''); 
    var configValue = 5; 

    miniCartTotal = parseFloat(miniCartTotalString) + configValue;
    console.log("updated value " + miniCartTotal);

    $("#estimated-amount-due .content").html("$" + miniCartTotal.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
});

#10


0  

best and simple way to format the number is to use java-script function

格式化数字的最佳和简单方法是使用java脚本函数

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

有关更多信息,请单击文档页面