Why conversions between string to int not working as expected for numbers divisible by 10?

Go To StackoverFlow.com

0

If parseInt is used inside the 'for' loop, it works for all cases. But in this example, it is not working properly for cases like 99-100 or 999-1000. What happens here? Is the implicit conversion wrong?

function buggy10000(value)
{
    var r = value.split("-");
    var len=r.length;
    var j;
    if(len==2)
    {
        console.log("For in RANGE " + r[0]+"<-->"+r[1]);
        for(j=r[0];j<=r[1];j++)
        {
            console.log(j);
        }
    }

}

buggy10000("98-99");
buggy10000("99-100");  //for not working as expected
buggy10000("100-102");
2012-04-04 20:16
by No account
And "as expected" would be defined as... - Ed S. 2012-04-04 20:18
Problem reported for nodeJS - No account 2012-04-04 20:19
You're showing example calls but not their output, so it's hard to tell what you're actually seeing. Post the results of those calls and it might be more obvious what you're asking about - Herms 2012-04-04 20:22


6

because: "98" <= "99" (string comparison)

"100" <= "102"

but "99" > "100"

The conversion appears only when j++ is called, but for the second case (99-100) that never happens, because the loop condition fails.

2012-04-04 20:28
by mihai
yeap,thank you. Js is too dynamic for me :) A feeling of PHP : - No account 2012-04-05 19:46


0

function buggy10000(value)
{
    var r = value.split("-");
    var len=r.length;
    var j;
    if(len==2)
    {
        console.log("For in RANGE " + r[0]+"<-->"+r[1]);
        for(j=r[0]*1;j<=r[1]*1;j++) <----Modified
        {
            console.log(j);
        }
    }

}

Does it work?

2012-04-04 20:30
by Wei Ma
That will work because you are forcing a parseInt() on the string. The OP has already said that works - Andrew Leach 2012-04-04 20:33


0

This is a type conversion problem, and it's related to comparisons. You're passing strings to your function, splitting the string, then comparing them. JS is getting confused as you're comparing strings, not integers.

I rewrote your function as follows to explicitly parse those values as integers, and it's working as you expect now.

function buggy10000(value)
{
    var r = value.split("-");
    var len=r.length;
    var j;
    if(len==2)
    {
        console.log("For in RANGE " + r[0]+"<-->"+r[1]);
        r[0] = parseInt(r[0]);
        r[1] = parseInt(r[1]);
        for(j=r[0];j<=r[1];j++)
        {
            console.log(j);
        }
    }

}
2012-04-04 20:30
by dmp
Ads