Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two numbers 9<10

Tags:

jquery

I have never met this bug before , whenever my jquery script gets to compare the numbers 9 and 10 or 99 and 100 or 999 and 1000 with 9<10 or 99<100 or 999<1000 I get a faulty result , I get false instead of true. How do I fix this jquery bug ? Thank you.

Jquery:

interval = setInterval(function(){
                $.post('help/retrivetable.php', { tableimpulse : sessid } , 
                    function(watchaget) {
                        if (countcom < watchaget)
                        {
                            countcom = watchaget;
                            $.post('help/retrivetable.php', { newtableimpulse : sessid } , 
                                function(getit) {
                                    $("#chat").append("<p id="+countmsg+">"+getit+"</p>");
                                    var scrolldown = $('#chat')[0].scrollHeight;
                                    $('#chat').animate({scrollTop:scrolldown}, 200);
                            }); 
                        }
                }); 
            }, 50); 

When countcom = 9 and watchaget = 10 it should enter that if , but I treats it like they are equal and won't get in it.

like image 376
southpaw93 Avatar asked Nov 17 '25 20:11

southpaw93


1 Answers

jQuery is Javascript. If it is a bug, it is not a jQuery-Bug but a Javascript-Bug. (Edit: There is a discussion on this sentence. Read the comments)

Try this solution:

The variables are defined as strings:

var a = "9";
var b = "10";

This comparison will reproduce your result:

if (a < b) ...

When you compare two strings with the operator < you get true if the first operand will be sorted lexically before the second. You get this result, because in the lexical order a string starting with "1" will be sorted before a string starting with "9", regardless of its length.

Try this instead:

if (a-b < 0) ...

The term a-b forces javascript to process a numeric calculation. Strings will be converted into numbers.

like image 75
Hubert Schölnast Avatar answered Nov 19 '25 08:11

Hubert Schölnast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!