Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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('$', '')
    );
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading