Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

Can't compare two floating number in jquery

My code is:

function checking(data,ans,no){

    var results = data.split(','),i;
    ans = parseFloat(Math.round(ans* 100) / 100).toFixed(2);
    alert('correct : ' + results[--no]);
        alert('my ans: ' + ans);
        var correct = parseFloat(results[--no]);
        var givenAns = parseFloat(ans);
        var diff = correct - givenAns;
        alert(diff);
    if(correct == givenAns){
    alert('correct');
      $('#wrong'+ no).hide();
      $('#ok'+ no).show();
      setTimeout(function() { return true; }, 1500);
    }
    else{
    alert('not correct');
      $('#ok'+ no).hide();
      $('#wrong'+ no).show();
      var temp = no+1;
      $('#notSolveBtn'+ temp).show();
      return false;
    }

}

function check_ans(ans,no){
    $.get('AnswerSheet/1.txt', function(data) {
          checking(data,ans,no)
    }, 'text');
}

Problem:

alert('correct : ' + results[--no]);
            alert('my ans: ' + ans); 

this two lines alert correct : 115.38 my ans : 115.38 But ans == results[--no] always return false. Again I parse these two values into float type if there is any type mismatch issue. Still same problem. To be confirmed I subtract one from another:

 var diff = correct - givenAns;
            alert(diff);

but alert(diff); alert NAN which should alert 0.00 or 0. Whats wrong am I doing. Sorry if this problem already asked. I googled a lot of time but no luck.

Upvotes: 0

Views: 1490

Answers (1)

rst
rst

Reputation: 2724

First issue is you only parse ans and not result so add this here

resultFloat = parseFloat(result[no]).toFixed(2);

Second, I wouldn't use --no if you are not 100% certain of what you are doing. In your code you compare two different things, in the first alert you had a different entry of the array than in the parting var correct = .... So better just define the new no at one point and use that value for the following usage

function checking(data,ans,no){

    var results = data.split(','),i;
    no--;
    resultFloat = parseFloat(result[no]).toFixed(2);
    ans = parseFloat(Math.round(ans* 100) / 100).toFixed(2);
    alert('correct : ' + resultFloat); // <-- this one and...
        alert('my ans: ' + ans);
        var correct = resultFloat; // <-- ...this one were different before, was that on purpose?
        var givenAns = ans;
        var diff = correct - givenAns;
        alert(diff);
....

Upvotes: 1

Related Questions