skip to Main Content

im building a shopping cart for an application and im trying to get the total value of the sum between all the elements with the class ".totalPrice".

everything is working fine and the sum is being done correctly untill i try to sum values like 1.005.67 + 1.050.00, then the result is printed like this

enter image description here

this is my code:

function sum() {
  var sum = 0;
  $('.totalPrice').each(function () {
    sum += parseFloat(this.value);
  });
  $("#total").text("Total: $" + sum.toFixed(2).replace(".",","));        
}
<label>
<label> Value 1 </label>
<input type="text" class="totalPrice">
<br><br><br>
<label> Value 2 </label>
<input type="text" class="totalPrice">
<br><br><br>
<button onclick="sum()"> calculate </button>
<h1 id="total"> </h1> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

2

Answers


  1. It’s because there are two decimal places within your inputs.

    When you run parseFloat("1.005.67"), you get 1.005; and, from `parseFloat("1.050.00"), you get 1.05.

    Adding these numbers together, you get 2.055, which you’re then rounding to 2 decimal places, hence the result $2.05.

    For the number to parse as you expect, the inputs must have only one decimal point.

    Login or Signup to reply.
  2. Create an instance of Intl.NumberFormat and set it to currency.

    Please, name variables appropriately. Do not have a variable and function with identical names. It is confusing for the reader.

    Noe: If you set your <input> to type="number", you can set the step to account for 1/100ths and you can now grab the input value without parsing, with input.valueAsNumber.

    const currencyFormatter = new Intl.NumberFormat('en-US',
      { style: 'currency', currency: 'USD' });
    
    const calculateSumAndDisplay = () => {
      const sum = [...document.querySelectorAll('.totalPrice')]
        .reduce((total, input) => total + input.valueAsNumber, 0);
      document.querySelector('#total')
        .textContent = `Total: ${currencyFormatter.format(sum)}`;        
    }
    <label>Value 1</label>
    <input type="number" class="totalPrice" step="0.01" />
    <br>
    <label>Value 2</label>
    <input type="number" class="totalPrice" step="0.01" />
    <br>
    <button type="button" onclick="calculateSumAndDisplay()">Calculate</button>
    <h1 id="total"></h1> 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search