• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Adding the negative number return as Nan

Jailani24589

New Coder
Getting the values from the locator like below, if the locator have the negative values Total return NaN

JavaScript:
for (let i = 0; i < count-2; i++)
        {
            let estimateMiniCartAmount = (await _estimateTotalAmount.nth(i).innerText).replace('$','').replace('/mo', '').replace('.00','')
            console.log(" Line Amount-->"+ estimateMiniCartAmount)
            Total = parseFloat(Total) + parseFloat(Number(estimateMiniCartAmount))
            console.log(" Line Amount-->"+ Total)
        }

Output

Line Amount-->90
Line Amount-->90
Line Amount-->−25
Line Amount-->NaN
 

Antero360

King Coder
Staff Team
Security Analyst
Getting the values from the locator like below, if the locator have the negative values Total return NaN

JavaScript:
for (let i = 0; i < count-2; i++)
        {
            let estimateMiniCartAmount = (await _estimateTotalAmount.nth(i).innerText).replace('$','').replace('/mo', '').replace('.00','')
            console.log(" Line Amount-->"+ estimateMiniCartAmount)
            Total = parseFloat(Total) + parseFloat(Number(estimateMiniCartAmount))
            console.log(" Line Amount-->"+ Total)
        }

Output

Line Amount-->90
Line Amount-->90
Line Amount-->−25
Line Amount-->NaN
Hi there,
You might want to check if Total is a number first of all
 

cbreemer

King Coder
I am not sure why this returns NaN instead of the expected 65. However this simplified code

JavaScript:
var total = 0;

function add(amount)
{
    total += parseFloat(Number(amount));
    console.log("amount = " + amount + "  total = " + total);
}

add("90");
add("-25");

produces the correct output :

amount = 90 total = 90 amount = -25 total = 65

I don't know what made the difference :rolleyes: but maybe it helps.

Two questions:
1) Any reason for using the await ?
2) Any reason for using the Number() function ? It works just as well without it.
 
Top