skip to Main Content

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


  1. 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 be performInternationalSwiftPaymentsService?.bopSplit?.[i]?.randValue.

    The sum property should also be initialized to zero, else it will be undefined if not initialized.

    let totalZARForeign = 0;
    const performInternationalSwiftPaymentsService = {
      bopSplit: [{randValue: "1.12"},{randValue: "2.23"},{randValue:"3.42"}]
    };
    for (let i = 0; i < performInternationalSwiftPaymentsService.bopSplit.length; i++) {
        totalZARForeign += +(performInternationalSwiftPaymentsService.bopSplit[i].randValue);
    }
    console.log(totalZARForeign)
    Login or Signup to reply.
  2. Some of your data are not a number (can be undefined or a string) you can use some like

    this.totalZARForeign=0; //<--be sure starts with 0
    for (let i = 0; i < this.performInternationalSwiftPaymentsService.bopSplit.length; i++) {
        this.totalZARForeign += +(this.performInternationalSwiftPaymentsService.bopSplit[i].randValue || 0);
      }
    

    See the "+" and the ("value" || 0)

    BTW, generally we don’t use a loop for else reduce

    this.totalZARForeign=this.performInternationalSwiftPaymentsService.bopSplit
                               .reduce((a:number,b:any)=>a+(+(b||0)),0)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search