0

I want to make a simple addition of every span with the class .part-price, but when I do it comes out in infinite numbers.

This is my javascript (jquery) :

var total = 0;
  $(".part-price").each(function() {
    total += Number($(this).text());
  });
  $("#cart-total").text(total);

And this is my html :

<span class="part-price">0.86</span>
<span class="part-price">1.00</span>
<span>Total: </span><span id="cart-total">0</span>

At the moment I only have 2 value, one is 0.86, and the other is 1.00, it should come out as:

0.86 + 1.00 = 1.86

But with my code the result is:

0.86 + 1.00 = 1.8599999999999999

  • 1
    @NickParsons thank you, found the answer there, have to handle in cents to not have decimals and then convert to euros. – Ruben Tapadas Feb 03 '19 at 05:42

1 Answers1

1

Your issue is that you're not handling your floating point numbers properly. You can use .toPrecision to help deal with floating point issues.

See working example below:

var total = 0;
$(".part-price").each(function() {
  total += Number($(this).text());;
});

$("#cart-total").text(total.toPrecision(3));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="part-price">0.86</span>
<span class="part-price">1.00</span>
<span>Total: </span><span id="cart-total">0</span>

Do note: .toPrecision() will return a string instead of a number.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64