简体   繁体   中英

Adding floats with javascript

I'm using jQuery, and I want to sum up the values in my table column, everything seems to work fine, but my value is returned a string with all the values added like: 123.5013.0012.35

How can I sum these properly?

var totals

$(".add").each(function(i) {
  totals += parseFloat($(this).text()).toFixed(2);
});

console.log(totals);

You've got multiple errors there. One is not initializing totals to something numeric, like 0.0. The second is not realizing that .toFixed() returns a string. Javascript is concatenating the strings together, rather than adding numbers.

Basically the same question has been asked before as javascript-why-does-this-produce-and-ugly-string-i-would-like-currency and answers there should solve this for you.

Here is a working version (tested in firefox 3.5):

<!DOCTYPE html>
<html>
<head>
    <title>Sum of nubers</title>

    <script src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function(){
            var total = 0;
            $(".add").each(function(){
                total += parseFloat($(this).text());
            });
            alert(total.toFixed(2));
        });
    </script>
</head>
<body>
<div class="add">23.4567</div>
<div class="add">98.7654</div>
</body>
</html>

That is just one of the many ways to do it. Have a look at this question for several other methods:

How to convert strings to floats

var totals

$(".add").each(function(i) {
  totals += parseFloat($(this).text());
});

console.log(totals.toFixed(2));

possibly use Math.round, floor or ceil

Simple try this . its works for me.

    var totals= 0;
    $(".add").each(function() {
        if (jQuery(this).val() != '')
            totals= Number(totals) + Number(jQuery(this).val()); 
    });
   console.log(totals);

Looks like it's doing a string add. Try setting var totals = 0;

  function update_total() {
    var total = 0.0;
    $('.invoice_service_price').each(function(index){
      var val=parseFloat($(this).html().trim());
      if(!isNaN(val)) total += val;
    });
    alert("total="+total);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM