1

I have created a sample shopping cart that stores the data in localStorage and display it in the cart. The problem where I am stuck is the total of prices as it's kept on concatenating all the price values but not doing the SUM of it. Suppose, two items have prices 100$ & 600$ respectively then the total amount is coming as 100600.

How can I solve this problem?

HTML code:

<div class="total"></div>

JavaScript:

const cTotal = cartbox.querySelector('.total');
let cartTotal = '';
let price = '';

JSON.parse(localStorage.getItem("items")).map(data=>
{
    price = data.price;
    for(var i = 0; i < price.length; i++)
    {
        cartTotal += price[i];
    }
});
cartTotal = '<p class="amount">Total Amount: '+cartTotal+'</p>'

cTotal.innerHTML = cartTotal;
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Seems like you need to separate a price and a currency, and store a price as a `number`. – sergdenisov Apr 14 '21 at 16:41
  • In localStorage, the price is stored as a number, While displaying it.. I just have added a $ sign but I am fetching the prices in total from the localStorage i.e. int only – Jaspreet Singh Apr 14 '21 at 16:43
  • Hi @jaspreet Singh , try initializing cartTotal and price like let cartTotal = 0; let price '; you initialize it as string that's why its concatenating rather than sum – Priyanka Giri Apr 14 '21 at 16:44
  • Hello @priyankaGiri, I tried your method but still got similar result except a 0 got added infront of the value like this -> 0100600 – Jaspreet Singh Apr 14 '21 at 16:52
  • If you get a result like "0100600" then your `price[i]` is a `string` but not a `number`. – sergdenisov Apr 14 '21 at 17:01
  • @sergdenisov That can be the possibility, Do you know a way where I can parse the price as a int? – Jaspreet Singh Apr 14 '21 at 17:14
  • You can try `parseInt(price[i], 10)` for example, but it's better to store as a `number` in `localStorage`. It would be better if you could show your data JSON. – sergdenisov Apr 14 '21 at 17:24
  • @sergdenisov I used unary operator to convert string data to int and it finally worked. Now, the only problem I am currently facing is that to multiply it with quantity... I tried doing price = price + (data.price * data.no) (no is quantity) Then the total gets 0. any suggestions for this? – Jaspreet Singh Apr 14 '21 at 17:27
  • Create a working code snippet so we could debug it. – sergdenisov Apr 14 '21 at 17:34
  • `let cartTotal = '';` <-- empty string WHY? – epascarello Apr 14 '21 at 17:52
  • I admit, my bad.. That would be an int variable instead of string.. thanks to you guys, I made it work except some minor things anyways thanks again – Jaspreet Singh Apr 14 '21 at 17:54
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Apr 16 '21 at 07:26

4 Answers4

1

First off, in order to avoid type coersion, change this line

let cartTotal = '';

to this:

let cartTotal = 0;

Next, to force type coersion on the other end, change this line:

cartTotal += price[i];

to this:

cartTotal += Number.parseInt(price[i]);

or to support floats:

cartTotal += Number.parseFloat(price[i]);
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • Using this -> cartTotal += Number.parseInt(price[i]); is returning only two digit numbers of the value. Suppose, my price total is 1400 then it is returning 14. Any solutions without adding * 100 because it just mess the calculation? – Jaspreet Singh Apr 14 '21 at 17:37
  • You'll probably find that the raw values you're getting from localStorage are wrong. I recommend working with cents, and converting to dollars only at display time. – code_monk Apr 14 '21 at 20:16
1

Try:

let cartTotal = 0;
price = data.price;

for(var i = 0; i < price.length; i++)
{
  cartTotal += parseFloat(price[i]);
}

Full code:

HTML CODE: 
<div class="total"></div>


JavaScript:
 const cTotal = cartbox.querySelector('.total');
 let cartTotal = 0;
 let price = 0;

  JSON.parse(localStorage.getItem("items")).map(data=>
  {
      price = data.price;
      for(var i = 0; i < price.length; i++)
      {
            cartTotal += parseFloat(price[i]);
       }
   });
    cartTotal = '<p class="amount">Total Amount: '+cartTotal+'</p>'
           
    cTotal.innerHTML = cartTotal;
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
  • Using this -> cartTotal += Number.parseFloat(price[i]); is returning only two digit numbers of the value. Suppose, my price total is 1400 then it is returning 14. Any solutions without adding * 100 because it just mess the calculation? – Jaspreet Singh Apr 14 '21 at 17:42
  • 1
    Can you paste your `localStorage.getItem("items")` ? – Rashed Rahat Apr 14 '21 at 17:48
1

all you need is to add parseInt to make sure that your price is in number format besides that change your initial value of cartTotal to 0 like this

 const cTotal = cartbox.querySelector('.total');
 const parsedData = JSON.parse(localStorage.getItem("items")); 
 let cartTotal = 0;

 parsedData.map(data => {
      for(var i = 0; i < data.price.length; i++)
      {
          cartTotal += parseInt(data.price[i]);
      }
 });

 cartTotal = '<p class="amount">Total Amount: '+cartTotal+'</p>'          
 cTotal.innerHTML = cartTotal;

Note: if the prices may have numbers after the period use parseFloat instead

Joseph
  • 5,644
  • 3
  • 18
  • 44
0

Try this:

    price = data.price;
    cartTotal = price.reduce(function(a,b){
            return a+b;
          });
mac
  • 162
  • 1
  • 1
  • 11
  • Uncaught TypeError: price.reduce is not a function However, I used unary operator to convert string data to int as it was saved as a string in localStorage.. The only problem I am currently facing is that to multiply it with quantity... I tried doing price = price + (data.price * data.no) (no is quantity) Then the total gets 0. any suggestions for this? – Jaspreet Singh Apr 14 '21 at 17:24
  • Can You show the data input for this script? – mac Apr 14 '21 at 17:34
  • It's a bit long code but here's a glimpse addtocart[i].addEventListener("click", function(e){ if(typeof(Storage) !== 'undefined') { let item = { id:i+1, name:e.target.parentElement.children[2].textContent, price:e.target.parentElement.children[1].textContent, no:1, }; – Jaspreet Singh Apr 14 '21 at 17:40
  • if(JSON.parse(localStorage.getItem('items')) === null) { items.push(item); localStorage.setItem("items", JSON.stringify(items)); window.location.reload(); } – Jaspreet Singh Apr 14 '21 at 17:40
  • data.price is not an array. That's one of your problems – code_monk Apr 14 '21 at 20:18