I am trying to sum multiple decimals numbers together however when I console the result it is showing a concatenated result with an undefined in front of it
for (let i = 0; i < this.performInternationalSwiftPaymentsService.bopSplit.length; i++) {
this.totalZARForeign += this.performInternationalSwiftPaymentsService.bopSplit[i].randValue;
}
console.log(this.totalZARForeign)
console result –> undefined4752.861188.22
The result I want is for it to add 4752.86 and 1188.22 together in this example
Any idea what I am doing wrong. I also tried adding a parseFloat here this.totalZARForeign += parseFloat(this.performInternationalSwiftPaymentsService.bopSplit[i].randValue);
but then I get NaN in the console result
2
Answers
Please make sure that the property
randValue
is a number and not a string, else it will concatenate it as a string, hence this behaviour.You can use the unary operator
+
to convert the string to number if it is a string. Also make sure you null check the values using typesript safe check operator –?.
, so it will beperformInternationalSwiftPaymentsService?.bopSplit?.[i]?.randValue
.The sum property should also be initialized to zero, else it will be
undefined
if not initialized.Some of your data are not a number (can be undefined or a string) you can use some like
See the "+" and the ("value" || 0)
BTW, generally we don’t use a loop for else reduce