My javascript parseInt("08") surprise!

I recently had to debug a problem that was causing a javascript function to return the incorrect value. The code in question was right padding numbers less than 10 with a 0: so 1 became "01", 2 becomes "02" and 10 should be "10".
Number.prototype.to_s = function() {
    if (this < 10) {
        return '0' + this.toString();
    } else {
        return this.toString();
    }
}
This works fine... in one direction.
I kept running into a problem when I tried to parse this back into an integer.
So I'd do something like
parseInt(8.to_s())
and the result would be 0. What I didn't realize is that the "0" prefix when parsing an string indicates the number is base-8 (octal) and therefore "08" isn't a valid number. I would have, however expected some sort of error message or NaN instead of 0. The problem is that javascript will only return NaN if the first character in the string is not a number... so It happily saw that '0' was a number, but '8' was not (in base 8) so it returned 0.
Aside: I see that this method of specifying base-8 is not supposed to be deprecated

Comments

Michael Seery said…
Oh yes. I remember running into this problem ten years ago. Why on EARTH would the default behavior be magical radix guessing?
Anonymous said…
Please link to a better resource than w3schools, like https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

See http://w3fools.com/ for why.
Mike Mainguy said…
Interesting comment on w3schools, frankly, it was the firstly googled link that had a reasonable explanation. The mozilla docs are certainly better and actually recommend what my solution was (always force base 10)...

Thanks, I'll have to keep that in mind for future reference.
Tait said…
"is not supposed to be deprecated" should be "is supposed to be deprecated"?
Rob K said…
That shouldn't have been a surprise. This is how numbers have been interpreted forever. Leading 0 is octal, leading 0x is hex.
Unknown said…
This is explicitly covered in 'JavaScript: The Good Parts'. Definitely worth reading: there are lots of other horrors in there.

JavaScript: The Good Parts: The Awful Parts

Popular posts from this blog

the myth of asynchronous JDBC

The difference between Scalability, Performance, Efficiency, and Concurrency explained

Push versus pull deployment models