0
votes
I need to convert string to float to summarize all numbers and get the average.

I have tried Number(), parseFloat none of them are giving me the expected output.

For example instead of return 2 it is returning ‘11’

I am colleting data from this API: https://www.hatchways.io/api/assessment/students obs(to retrieve the data, I created a service: export class StudentsService {

studentsUrl: string = "https://www.hatchways.io/api/assessment/students";

constructor(private http: HttpClient) {}

//casting observable into Students array getAllStudents(): Observable<{students: Students[]}> { //return this.http.get(this.studentsUrl); return this.http.get<{students: Students[]}>(${this.studentsUrl}); } }

getAVG() {
for(let i = 0; i < this.students.length; i++) {
      //console.log('Estudante número: '+ i);
      for(let z = 0; z < 8; z++) {
        //console.log('Notas index: ' + z);
        this.grades[i] += Number(this.students[i].grades[z]);
        console.log('nota: '+ this.students[i].grades[z]);
      }
      var num = parseFloat(this.grades[0]);
      console.log('#######sum das notas######: ' + num);
    }
}

I need to sum all grades in the array to calculate the average and display it
2
Can you specify what you mean by "none of them have worked"?Nodir Rashidov
I was trying to say that Number() and parseFloat() have not worked.Andre Machado do Monte
Do not give me the expected output. For example: instead of 2 I am getting 11Andre Machado do Monte
@Henry i am not getting the expected output. For example instead of 2 I am getting 11Andre Machado do Monte

2 Answers

0
votes

You are on the right track with parseFloat() (parseInt() in this case would also work), it's just a matter of using it right.

You essentially want to go through each grade of the student.grades array and add its value to a sum that you'll later divide but the number of grades.

Something like this

this.students.forEach(student =>
{
    let sum = 0;
    student.grades.forEach(grade=>sum+=parseFloat(grade))  //Goes through each grade, parses it as float and add it's result to sum
    let avg = sum/student.grades.length;
})

Note: I'm using forEach to iterate through arrays, but using a regular for loop is fine as well. It's just a matter of preference here

There are other ways to get sum/average (array.reduce is one of them), but as long as you parse your string, anything is fine.

Here's a working Stackblitz of your scenario to illustrate.

If you have any questions let me know

0
votes

you have to initialize this.grades[i]=0; before you begin second loop(one with 'z).

for(let i = 0; i < this.students.length; i++) {
  //console.log('Estudante número: '+ i);

  this.grades[i]=0;

  for(let z = 0; z < 8; z++) {
    //console.log('Notas index: ' + z);
    this.grades[i] += Number(this.students[i].grades[z]);
    console.log('nota: '+ this.students[i].grades[z]);
  }
  var num = parseFloat(this.grades[0]);
  console.log('#######sum das notas######: ' + num);
}

}