Reputation: 1056
I have a problem with calculating a sum in typescript where I have 2 numbers that concatenate instead of summing it all up. I have looked up this issue and have seen several topics covering this problem where the solution usually was like this:
"use ParseInt()
or ParseFloat()
to convert your strings to integers"
The problem is that I don't have strings and even though that I use numbers they still concatenate.
My code is as follows:
updateSummaryAmount(index: number){
let summary = 0;
this.listOfPeriods[index].declarations.forEach(element => {
summary = summary + element.amount;
});
this.listOfPeriods[index].summary = summary;
}
If I sum
0,55
And
0,45
I get
00,550,45
When I try to use parseInt() or parseFloat(0 I get the following typescript error:
[ts} Argument of type 'number' is not assignable to parameter of type 'string'.
I have tried to sum with Math.floor()
, just to test, and this works but obviously gives me floored down numbers that I don't want.
How do I sum up 2 values in my case?
Upvotes: 0
Views: 3973
Reputation: 476
try below to force change element.amount to number
this.listOfPeriods[index].declarations.forEach(element => {
summary = summary + (+element.amount);
});
Upvotes: 6