0

I have an app that present invoice to the users, I have everything set except the total value of listed items in the invoice, I used the following code to sum the value but instead of getting sum , I got concatenated value

this.http.post('http://myurl',data,headers)
.map(res => res.json())
.subscribe(res => {
console.log(res)
 loader.dismiss()
this.items=res.server_response;

  this.totalAmount = this.getTotal();


});
});
 }
;
}

getTotal() {
    let total = 0;
    for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].amount) {
            total += this.items[i].amount;
            this.totalAmount = total;
        }
    }
    return total;
}

the display value is 0100035004000 for what suppose to be (1000+3500+4000)

LaideLawal
  • 77
  • 1
  • 10
  • The answer I provided to you is based on [this link](https://stackoverflow.com/questions/14667713/typescript-converting-a-string-to-a-number) which will help explain what is going on. – Philip Brack Nov 06 '17 at 21:52
  • 1
    Possible duplicate of [TypeScript Converting a String to a number](https://stackoverflow.com/questions/14667713/typescript-converting-a-string-to-a-number) – Suraj Rao Nov 07 '17 at 05:11

2 Answers2

0

parse items.amount to number by adding +:

getTotal() {
 let total = 0;
 for (var i = 0; i < this.items.length; i++) {
    if (this.items[i].amount) {
        total += +this.items[i].amount;
        this.totalAmount = total;
    }
 }
 return total;
}
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
0

Instead of total += this.items[i].amount; which appears to concat the numbers as strings, change it to total += Number(this.items[i].amount); to convert from string to number in typescript.

Philip Brack
  • 1,340
  • 14
  • 26