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".
I kept running into a problem when I tried to parse this back into an integer.
So I'd do something like
Aside: I see that this method of specifying base-8 isnot supposed to be deprecated
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
Comments
See http://w3fools.com/ for why.
Thanks, I'll have to keep that in mind for future reference.
JavaScript: The Good Parts: The Awful Parts