김진오
김진오

Reputation: 79

javascript error when compare two number

When I call this function a strange error occurs.

So I added two sentences in my code to find out what was the problem. First one is alert(result); in 6 line and the second one is alert(wordbook_info_percentage+">="+result); in 12 line then I execute my code and I found out that result variable is "100.0" and "wordbook_info_percentage>=result" condition in "info_change_frame" function becomes true when wordbook_info_percentage is 2.0 and result is 100.0 I can't understand why 2.0>=100.0 is true. What is my mistake? Please help me.

function word_book_info_change_1(){
    var wordbook_info_percentage=parseFloat(($('#wordbook_info_1').text()).replace('%','')).toFixed();
    arr[0]=43;

    var result=parseFloat((parseInt(arr[0])+parseInt(word_number))*100/parseInt(arr[1])).toFixed(1);    
    alert(result);

    var info_change_1_repeat=setInterval(info_change_frame,10);

    function info_change_frame(){
        if(wordbook_info_percentage>=result){
            alert(wordbook_info_percentage+">="+result);
            ClearInterval(info_change_1_repeat);
        }
        else{
            wordbook_info_percentage=(parseFloat(wordbook_info_percentage)+0.1).toFixed(1);
            $('#wordbook_info_1').text(wordbook_info_percentage+"%");
        }
    }
}

Upvotes: 0

Views: 334

Answers (2)

Rahul
Rahul

Reputation: 482

"2.0">="100.0"
true
2.0>100.0
false
parseInt("2.0")>parseInt("100.0")
false

i think you should parse the value to int .

function word_book_info_change_1(){
    var wordbook_info_percentage=parseFloat(($('#wordbook_info_1').text()).replace('%','')).toFixed();
    arr[0]=43;

    var result=parseFloat((parseInt(arr[0])+parseInt(word_number))*100/parseInt(arr[1])).toFixed(1);    
    alert(result);

    var info_change_1_repeat=setInterval(info_change_frame,10);

    function info_change_frame(){
        if(parseInt(wordbook_info_percentage)>=paseInt(result)){
            alert(wordbook_info_percentage+">="+result);
            ClearInterval(info_change_1_repeat);
        }
        else{
            wordbook_info_percentage=(parseFloat(wordbook_info_percentage)+0.1).toFixed(1);
            $('#wordbook_info_1').text(wordbook_info_percentage+"%");
        }
    }
}

Upvotes: 3

Martin Adámek
Martin Adámek

Reputation: 18359

You are converting those numbers to string with number.toFixed(1). Comparing strings with numbers uses radix sorting, that is the reason why you are confused by the comparation.

Just move the toFixed call to the end where you set the value to some DOM.

var a = 12.345;
var b = 5.35;

console.log(a, b);
console.log(a.toFixed(1), b.toFixed(1));
console.log(a > b);
console.log(a.toFixed(1) > b.toFixed(1));

Upvotes: 1

Related Questions