-1

Hi i am working on javascript and here i am working on sum of float numbers but i am getting wrong result

var studentsList = [
  { name: 'A', rollNo: 1, mark: "6.75" },
  { name: 'B', rollNo: 2, mark: "3.5" },
  { name: 'C', rollNo: 3, mark: "4.25" },
  { name: 'A', rollNo: 1, mark: "3.5" }
];

var byName1 = {};
for (var student of studentsList) {
  if (student.name in byName1) {
    byName1[student.name].mark += parseFloat(student.mark);
  } else {
    byName1[student.name] = { ...student };
  }
}
console.log(Object.values(byName1));

But the actual result is 10.25.

How to do it? TIA.

  • The problem is that in your `studentsList`, you actually have strings instead of numbers. You need to convert those into numbers first. – Jesper Apr 09 '21 at 11:51

1 Answers1

1

You need to parseFloat the byName1[student.name].mark too, to do addition with parseFloat(student.mark) because byName1[student.name].mark is a string.

var studentsList = [
  { name: 'A', rollNo: 1, mark: "6.75" },
  { name: 'B', rollNo: 2, mark: "3.5" },
  { name: 'C', rollNo: 3, mark: "4.25" },
  { name: 'A', rollNo: 1, mark: "3.5" }
];

var byName1 = {};
for (var student of studentsList) {
  if (student.name in byName1) {
    byName1[student.name].mark = parseFloat(byName1[student.name].mark) + parseFloat(student.mark);
  } else {
    byName1[student.name] = { ...student };
  }
}
console.log(Object.values(byName1));

But if you use float instead of string for the mark it'd be cleaner.

Silidrone
  • 1,471
  • 4
  • 20
  • 35