Home > database >  Set variable type to number but still get a NaN in output
Set variable type to number but still get a NaN in output

Time:10-21

I am having an issue with a Nan error in my typescript. I have set a variable type to number and loop throuh an element where I get all the different balance amounts. They come in the form of "$..." like $10.00 and $20.00, so I do a replace and then finally include each balance amount into the total sum balance variable.

However, in my console log it outputs:

Expected: NaN
Actual: 20.00

I am not sure why that is. Why does it think it's not a number and how can this be rectified (should show 20.00)

balance: Selector;

 this.balance = Selector('.balance');
 this.balanceTotal = Selector('.balance-total ');

  async validateTotalBalance() {

    let sumBalanceTotal: number = 0;
    for (let i = 0; i < (await this.balance.count); i  ) {
      let amount = await this.balance.nth(i).textContent;
      amount.replace('$', '');
      let convertedAmount = Number(amount);
      convertedAmount.toFixed(2);
      sumBalanceTotal  = convertedAmount;
    }

    console.log('Expected: '   sumBalanceTotal);
    console.log(
      'Actual: '   (await this.balanceTotal.textContent).replace('$', '')
    );
}

CodePudding user response:

amount.replace('$', '');

This line is not storing the result of the replace so amount still has $ in it after, which could be why the value is NaN

CodePudding user response:

This is because toFixed() returns a string. Use toFixed() until calculations are done or only before you need to present the data.

  • Related