Home > Software engineering >  Average Calculation not Working Well, Result is always NaN
Average Calculation not Working Well, Result is always NaN

Time:08-08

i was trying to do a calculation to find the average of the price from the array but i seem to be getting NaN, How do i solve it ?

var array = [ ];

var sum = 0;   
setInterval (function() { 
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=ETHEUR')

    .then(response => {
        return response.json();
    })
    .then(data => {
        array = array.slice(0,10).concat([data.price]);
    });

    for (var number of array) {
        sum  = number;
    }
    average = sum / array.length;
    console.log("Average of ETH/EUR every 10 seconds is: "  average);
    document.getElementById("avgStock").innerHTML= average; 



},10000);

This is the result in the console.log

CodePudding user response:

Use parseFloat to convert the return of the string coming from the API to float, so that you can so arithmetic operations.

var array = [ ];

var t = setInterval (function() { 
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=ETHEUR')

    .then(response => {
        return response.json();
    })
    .then(data => {
        array = array.slice(0,10).concat([parseFloat(data.price)]);
    });

    const sum = array.reduce((partialSum, a) => partialSum   a, 0);
    if(array.length == 0){
        console.log("Average of ETH/EUR every 10 seconds is: "  0);
        document.getElementById("avgStock").innerHTML= 0; 
    }
    else{
        average = sum / array.length;
        console.log("Average of ETH/EUR every 10 seconds is: "  average);
        document.getElementById("avgStock").innerHTML= average; 
    }

},10000);

Also, I updated the sum logic. It'll help you to calculate the sum in one line without running a loop.

CodePudding user response:

I can see its printing the Average correctly first time, but giving NaN afterwards.

Average of ETH/EUR every 10 seconds is: 1682.39
Average of ETH/EUR every 10 seconds is: NaN

Please do console.log() for data, array and sum. If any of these values giving null or NaN that would be the issue to generate NaN for the Average.

CodePudding user response:

I believe the problem is your sum you're doing:

for (var number of array) {
  sum  = number;
}

but the number in the array is a string.

You need to parse the number first. There's a nifty shorthand, try this:

for (var number of array) {
  sum  =  number; //<- note the  number (parsing this to a number)
}

Or update the array:

array = array.slice(0,10).concat([ data.price]); //<- added a   to parse the price 

Ideally the data should be coming down from the API in the correct format. I would advocate for fixing the API instead of parsing values

  • Related