0

I'm working on an E-learning project and I need to have a simple verification function which takes 3 arrays and return true when each element in the 3rd array is equal to the 1st array corresponding element multiplied by the 2nd array element.

The 3 arrays have the same length.

Examples:

verifyNotes([5], [2], [11])
//should return false because 5*2=10
verifyNotes([5], [2], [10])
//should return true

This is the function I created (I think that nothing is special):

function verifyNotes(coefficients, notes, savedResults){
 var resultVerif=true;
 savedResults.forEach(function(element, i){
  if( (coefficients[i]*notes[i]) !== savedResults[i] ){
   resultVerif=false;
  }
 });
 return resultVerif;
}

var verif1 = verifyNotes([1,4,2], [12,16,8], [12,64,16]);
console.info("Verif1: Are notes okay?", verif1);

The problem

When I have float notes, the function is returning false when it should return true (since 1.5*15.66=23.49) in this example:

var verif2 = verifyNotes([1,4,2,1.5], [12,16,8,15.66], [12,64,16,23.49]);
console.info("Verif2: Are notes okay?", verif2);
//ouputs: Verif2: Are notes okay? false

What is going wrong?

Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65

3 Answers3

4

It's a rounding error. You may want to round your number to a fixed amount of digits, like this:

parseFloat((your_number).toFixed(2));

Specifically, at if( parseFloat((coefficients[i]*notes[i]).toFixed(2))

Simon Visser
  • 364
  • 3
  • 14
1

Because floats arithmetics is not accurate in JavaScript.

http://www.w3schools.com/js/tryit.asp?filename=tryjs_inaccurate2

Here is some offered solution:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_inaccurate3

easy
  • 320
  • 1
  • 10
0

It could be must fixed, the result, like your are using it https://www.google.es/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=javascript+toFixed

Becouse, the round result decimal is to 2

tks

Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21