sanjeev singh
sanjeev singh

Reputation: 33

.each(function () not working for float values

The output should be 543.54 but I am getting 542.00. Please help me fix what have I done wrong. Thank you in Advance.

function getTotal() {
  var gtotal = 0.00;
  $(".sub_total").each(function() {
    subtotal = $(this).html() | 0;
    gtotal = parseFloat(gtotal) + parseFloat(subtotal);
  });
  var gtotal = gtotal.toFixed(2);
  $(".grand_total").html(gtotal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sub_total">267.33</div>
<div class="sub_total"></div>
<div class="sub_total">252.55</div>
<div class="sub_total">23.66</div>
<div class="grand_total"></div>
<a href="javascript:void(0);" onclick="getTotal()">Sum</a>

Upvotes: 1

Views: 40

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386720

You take a bitwise OR | instead of a logical OR || for a default value.

The bitwise OR converts to a 32bit integer value and performs an OR operation with the values.

function getTotal() {
  var gtotal = 0;                    // 0
  $(".sub_total").each(function() {
    subtotal = +$(this).html() || 0; // default value
    gtotal = gtotal + subtotal;      // no need to convert numbers again to numbers
  });
  var gtotal = gtotal.toFixed(2);
  $(".grand_total").html(gtotal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sub_total">267.33</div>
<div class="sub_total"></div>
<div class="sub_total">252.55</div>
<div class="sub_total">23.66</div>
<div class="grand_total"></div>
<a href="javascript:void(0);" onclick="getTotal()">Sum</a>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

The issue is because you're using a bitwise OR operator, not a logical OR operator.

Note that you can tidy up the logic by using += to increment the gtotal, joining the last two lines in to one, and using unobtrusive event handlers instead of the ugly on* event attribute:

$(function() {
  $('#sum').click(function(e) {
    e.preventDefault();
    var gtotal = 0.00;

    $(".sub_total").each(function() {
      subtotal = $(this).html() || 0; // note || here
      gtotal += parseFloat(subtotal);
    });

    $(".grand_total").html(gtotal.toFixed(2));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sub_total">267.33</div>
<div class="sub_total"></div>
<div class="sub_total">252.55</div>
<div class="sub_total">23.66</div>
<div class="grand_total"></div>
<a href="#" id="sum">Sum</a>

Upvotes: 2

Related Questions