Adventures in JavaScript number parsing(mir.aculo.us)
mir.aculo.us
Adventures in JavaScript number parsing
http://mir.aculo.us/2010/05/12/adventures-in-javascript-number-parsing/
5 comments
I don't like abusing String prototype but:
String.prototype.toInt=function(){ return parseInt(this,10) }
then: "08".toInt() // ==> 8Hmm... I think you might find this a little more flexible in the long run:
String.prototype.toInt = function (base) {
if (typeof base == 'undefined') base = 10;
return parseInt(this, base);
}
Smart defaults are always best, but there's no real need to handicap the users of your API.I wonder what made the original coder on javascript assume that base10 should not ALWAYS be the default unless told otherwise.
At least all the different browsers' versions of javascript are consistent about that (right?)
At least all the different browsers' versions of javascript are consistent about that (right?)
Yes, they should be consistent. Afaik. Thank science that other languages are better in that regard (here's Ruby):
irb(main):002:0> "08".to_i => 8 irb(main):003:0> "08".to_i(8) => 0
irb(main):002:0> "08".to_i => 8 irb(main):003:0> "08".to_i(8) => 0
This is not unique to Javascript. To a Java programmer this behavior seems natural(octal literals lead with a 0) and not really worthy of a angry blog post.
Well, it also parses hex numbers prefixed with 0x... Hard to be surprised after the first time you get tripped by it.
A couple of other odd cases: +[] evaluates to 0, while +{} evaluates to NaN (parseInt([], 10) evaluates to NaN). +new Date evaluates to the integer representation of the current Unix timestamp; parseInt(new Date, 10) evaluates to NaN.